I have a problem with the state of my context when updating a state that is an array.
The issue is the following, I have an object which stores the days selected by the user and which can be removed one by one. When removing one it does not update the react state and does not execute the useEffect.
// context/index.tsx
export const MyAppContext = ({children}: any) => {
const [afterSchool, setAfterSchool] = useReducer(afterSchoolReducer, initialAfterSchoolState);
return (
<AppContext.Provider value={{afterSchool, setAfterSchool}}>
{children}
</AppContext.Provider>
)
}
// context/reducer/after-school.reducer.ts
export const afterSchoolReducer = (state: IAfterSchoolState, action: IAfterSchoolAction): IAfterSchoolState => {
const { type, payload } = action;
switch (type) {
case 'removeSchedule': {
const { removeDate } = payload;
if (!removeDate) return state;
const updatedSelectedDays = state.type.selectedDays.filter(date => date !== removeDate);
return {
...state,
type: {
...state.type,
selectedDays: [...updatedSelectedDays],
},
};
};
case "updateServiceTypes":
console.log("updateServiceTypes type:", state.type)
const newTypes = state.service.types.map(type =>
(type.id === state.type.id)
? state.type
: type
);
return {
...state,
service: {
...state.service,
types: newTypes
}
};
default:
return state;
}
// hooks/after-school.ts
export const useAfterSchool = () => {
const { afterSchool: { type, service }, setAfterSchool } = useAppContext();
const handleDateRemove = (date: string) => {
setAfterSchool({ type: "removeSchedule", payload: { removeDate: date } });
setAfterSchool({ type: "updateServiceTypes", payload: {} });
};
useEffect(() => {
console.log("type:", type);
}, [type]);
}