Skip to content

Instantly share code, notes, and snippets.

@ojknation
Created October 14, 2022 16:51
Show Gist options
  • Save ojknation/c206712d9bac67948f632e0026069280 to your computer and use it in GitHub Desktop.
Save ojknation/c206712d9bac67948f632e0026069280 to your computer and use it in GitHub Desktop.
React context with useReducer Example
import { useContext } from "react";
import { WorkoutsContext } from "../context/WorkoutContext";
export const useWorkoutContext = () => {
const context = useContext(WorkoutsContext);
if (!context) {
throw Error(`Context cannot be used outside it's provider`);
}
return context;
};
import { createContext, useReducer } from "react";
export const WorkoutsContext = createContext();
const workoutsReducer = (state, action) => {
switch (action.type) {
case "SET_WORKOUTS":
return {
workouts: action.payload,
};
case "CREATE_WORKOUT":
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 WorkoutContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(workoutsReducer, { workouts: null });
return (
<WorkoutsContext.Provider value={{ ...state, dispatch }}>
{children}
</WorkoutsContext.Provider>
);
};
import { useAuthContext } from "../hooks/useAuthContext";
import { useWorkoutContext } from "../hooks/useWorkoutContext";
const WorkoutDetails = ({ workout }) => {
const { dispatch } = useWorkoutContext();
const { user } = useAuthContext();
const handleClick = async () => {
if(!user){
return
}
const response = await fetch("/api/workouts/" + workout._id, {
method: "DELETE",
headers: {
Authorization: `Bearer ${user.token}`
},
});
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>
<span onClick={handleClick}>delete</span>
</div>
);
};
export default WorkoutDetails;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment