Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

109
Views
inability to add an item in empty array using sate reducer function?

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;
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!