I am facing an issue in my React application where the state within a React context is not updating immediately, but only after I reload the page. I think maybe it’s wrong in the UPDATE case in WorkoutsContext.jsx
WorkoutsContext.jsx
const workoutsReducer = (state, action) => {
switch (
action.type
) {
..
case "UPDATE_WORKOUT":
return {
workouts: state.workouts.map((w) => (w._id === action.payload._id ? action.payload : w)),
};
..
}
};
const WorkoutContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(workoutsReducer, {
workouts: null,
});
return <WorkoutsContext.Provider value={{ ...state, dispatch }}>{children}</WorkoutsContext.Provider>;
};
UpdateModal.jsx
const UpdateModal = ({ closeModal, initialValues }) => {
..
const { dispatch } = useWorkoutsContext();
const handleSubmit = async (e) => {
e.preventDefault();
..
const response = await fetch("api/workouts/" + initialValues.id, {
method: "PATCH",
body: JSON.stringify(updatedWorkout),
headers: {
"Content-Type": "application/json",
},
});
const json = await response.json();
..
if (response.ok) {
console.log("workout updated");
dispatch({ type: "UPDATE_WORKOUT", payload: json });
}
};