Skip to content

ready to MERN Authentication Tutorial #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: lesson-11
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion backend/.env
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
PORT=4000
MONGO_URI=mongodb+srv://mario:test12345@mernapp.2susood.mongodb.net/merndb?retryWrites=true&w=majority
MONGO_URI=mongodb+srv://Feelings:MN123456@mernapp.qv7xqpq.mongodb.net/?retryWrites=true&w=majority
50 changes: 35 additions & 15 deletions backend/controllers/workoutController.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const mongoose = require('mongoose')

// get all workouts
const getWorkouts = async (req, res) => {
const workouts = await Workout.find({}).sort({createdAt: -1})
const workouts = await Workout.find({}).sort({ createdAt: -1 })

res.status(200).json(workouts)
}
Expand All @@ -13,21 +13,38 @@ const getWorkout = async (req, res) => {
const { id } = req.params

if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(404).json({error: 'No such workout'})
return res.status(404).json({ error: 'No such workout' })
}

const workout = await Workout.findById(id)

if (!workout) {
return res.status(404).json({error: 'No such workout'})
return res.status(404).json({ error: 'No such workout' })
}

res.status(200).json(workout)
}

// create a new workout
const createWorkout = async (req, res) => {
const {title, load, reps} = req.body
const { title, load, reps } = req.body

let emptyFields = []

if (!title) {
emptyFields.push('title')
}
if (!load) {
emptyFields.push('load')
}
if (!reps) {
emptyFields.push('reps')
}
if (emptyFields.length > 0) {
return res
.status(400)
.json({ error: 'Please fill in missing fields', emptyFields })
}

// add to the database
try {
Expand All @@ -43,13 +60,13 @@ const deleteWorkout = async (req, res) => {
const { id } = req.params

if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).json({error: 'No such workout'})
return res.status(400).json({ error: 'No such workout' })
}

const workout = await Workout.findOneAndDelete({_id: id})
const workout = await Workout.findOneAndDelete({ _id: id })

if(!workout) {
return res.status(400).json({error: 'No such workout'})
if (!workout) {
return res.status(400).json({ error: 'No such workout' })
}

res.status(200).json(workout)
Expand All @@ -60,15 +77,18 @@ const updateWorkout = async (req, res) => {
const { id } = req.params

if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).json({error: 'No such workout'})
return res.status(400).json({ error: 'No such workout' })
}

const workout = await Workout.findOneAndUpdate({_id: id}, {
...req.body
})
const workout = await Workout.findOneAndUpdate(
{ _id: id },
{
...req.body,
},
)

if (!workout) {
return res.status(400).json({error: 'No such workout'})
return res.status(400).json({ error: 'No such workout' })
}

res.status(200).json(workout)
Expand All @@ -79,5 +99,5 @@ module.exports = {
getWorkout,
createWorkout,
deleteWorkout,
updateWorkout
}
updateWorkout,
}
7 changes: 4 additions & 3 deletions backend/package.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "nodemon server.js"
"dev": "nodemon server.js",
"start": "node server.js"
},
"keywords": [],
"author": "",
Expand All @@ -14,5 +14,6 @@
"dotenv": "^16.0.1",
"express": "^4.18.1",
"mongoose": "^6.3.5"
}
},
"description": ""
}
18 changes: 18 additions & 0 deletions frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^13.5.0",
"date-fns": "^2.29.1",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-router-dom": "^6.3.0",
Expand Down
2 changes: 2 additions & 0 deletions frontend/public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0" />

<title>React App</title>
</head>
<body>
Expand Down
35 changes: 31 additions & 4 deletions frontend/src/components/WorkoutDetails.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,40 @@
import { useWorkoutsContext } from '../hooks/useWorkoutsContext'
// date fns
import formatDistanceToNow from 'date-fns/formatDistanceToNow'

const WorkoutDetails = ({ workout }) => {
const { dispatch } = useWorkoutsContext()

const handleClick = async () => {
const response = await fetch('/api/workouts/' + workout._id, {
method: 'DELETE',
})
const json = await response.json()

if (response.ok) {
dispatch({ type: 'DELETE_WORKOUT', payload: json })
}
}

return (
<div className="workout-details">
<h4>{workout.title}</h4>
<p><strong>Load (kg): </strong>{workout.load}</p>
<p><strong>Number of reps: </strong>{workout.reps}</p>
<p>{workout.createdAt}</p>
<p>
<strong>Load (kg): </strong>
{workout.load}
</p>
<p>
<strong>Number of reps: </strong>
{workout.reps}
</p>
<p>
{formatDistanceToNow(new Date(workout.createdAt), { addSuffix: true })}
</p>
<span className="material-symbols-outlined" onClick={handleClick}>
delete
</span>
</div>
)
}

export default WorkoutDetails
export default WorkoutDetails
41 changes: 23 additions & 18 deletions frontend/src/components/WorkoutForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,57 +8,62 @@ const WorkoutForm = () => {
const [load, setLoad] = useState('')
const [reps, setReps] = useState('')
const [error, setError] = useState(null)
const [emptyFields, setEmptyFields] = useState([])

const handleSubmit = async (e) => {
e.preventDefault()

const workout = {title, load, reps}
const workout = { title, load, reps }

const response = await fetch('/api/workouts', {
method: 'POST',
body: JSON.stringify(workout),
headers: {
'Content-Type': 'application/json'
}
'Content-Type': 'application/json',
},
})
const json = await response.json()

if (!response.ok) {
setError(json.error)
setEmptyFields(json.emptyFields)
}
if (response.ok) {
setEmptyFields([])
setError(null)
setTitle('')
setLoad('')
setReps('')
dispatch({type: 'CREATE_WORKOUT', payload: json})
dispatch({ type: 'CREATE_WORKOUT', payload: json })
}

}

return (
<form className="create" onSubmit={handleSubmit}>
<form className="create" onSubmit={handleSubmit}>
<h3>Add a New Workout</h3>

<label>Excersize Title:</label>
<input
type="text"
onChange={(e) => setTitle(e.target.value)}
<input
type="text"
onChange={(e) => setTitle(e.target.value)}
value={title}
className={emptyFields.includes('title') ? 'error' : ''}
/>

<label>Load (in kg):</label>
<input
type="number"
onChange={(e) => setLoad(e.target.value)}
<input
type="number"
onChange={(e) => setLoad(e.target.value)}
value={load}
className={emptyFields.includes('load') ? 'error' : ''}
/>

<label>Number of Reps:</label>
<input
type="number"
onChange={(e) => setReps(e.target.value)}
value={reps}
<input
type="number"
onChange={(e) => setReps(e.target.value)}
value={reps}
className={emptyFields.includes('reps') ? 'error' : ''}
/>

<button>Add Workout</button>
Expand All @@ -67,4 +72,4 @@ const WorkoutForm = () => {
)
}

export default WorkoutForm
export default WorkoutForm
24 changes: 15 additions & 9 deletions frontend/src/context/WorkoutsContext.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,36 @@
import { createContext, useReducer } from 'react'



export const WorkoutsContext = createContext()

export const workoutsReducer = (state, action) => {
switch (action.type) {
case 'SET_WORKOUTS':
return {
workouts: action.payload
return {
workouts: action.payload,
}
case 'CREATE_WORKOUT':
return {
workouts: [action.payload, ...state.workouts]
return {
workouts: [action.payload, ...state.workouts],
}
case 'DELETE_WORKOUT':
return {
workouts: state.workouts.filter((w) => w._id !== action.payload._id),
}
default:
return state
}
}

export const WorkoutsContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(workoutsReducer, {
workouts: null
const [state, dispatch] = useReducer(workoutsReducer, {
workouts: null,
})

return (
<WorkoutsContext.Provider value={{ ...state, dispatch }}>
{ children }
{children}
</WorkoutsContext.Provider>
)
}
}
5 changes: 4 additions & 1 deletion frontend/src/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -96,4 +96,7 @@ div.error {
color: var(--error);
border-radius: 4px;
margin: 20px 0;
}
}
input.error {
border: 1px solid var(--error);
}