I have this state , reducer modules , the point of doing this is to created 2 states the are relative one to another , in first action (add box) I add to the first state box an element and also created an empty array in the other state children, that will get filled with element once the second function will be called (on demand). the problem is I am not able to push items when the second function is called in to the empty array that is the result of the first function being called, could you help me with syntax ?
export default (state, action) => {
switch (action.type) {
case ADD_BOX:
return {
...state,
boxes: [...state.boxes, { id: action.id, index: action.index }],
childern: [...state.childern, []],
};
case ADD_CHILD:
return {
// push data in to already existing array !!
...state,
...state.childern[action.index[{ id: action.payload }]],
};
default:
return state;
}
};
// State Module
const AppState = (props) => {
const initialState = {
boxes: [],
childern: [],
};
const [state, dispatch] = useReducer(AppReducer, initialState);
console.log(state);
const AddBox = (id, i) => {
dispatch({
type: ADD_BOX,
id: id,
index: i,
});
};
const AddBoxChild = (id, i) => {
dispatch({
type: ADD_CHILD,
payload: id,
index: i,
});
};
return (
<appContext.Provider
value={{
boxes: state.boxes,
childern: state.childern,
AddBox,
AddBoxChild,
}}
>
{props.children}
</appContext.Provider>
);
};
export default AppState;
This is how you would add something to the children array
case ADD_CHILD:
return {
// push data in to already existing array !!
...state,
childern: [...state.childern, action.index[{ id: action.payload }]],
};
Also don't do this in ADD_BOX
childern: [...state.childern, []], // [[]] <- this is the result
You are adding an array to the array (nesting arrays)