2

I have following React State:

state: {
   objectOne: {
      arrayOne: [
         {
            arrayTwo: [
                {
                   value: 'some value'
                }
            ]         
         }
      ]
   }
}

I am using React useContext and the useReducer hooks. What I want to do is to add an object to arrayTwo.

What I have tried so far:

I call a dispatch function with the type of "ADD_NEW_OBJECT" and the payload is an object with some key value pairs in it.

    dispatchFunction({
       type: 'ADD_NEW_OBJECT', 
       payload: {
          value: {
             a: 'this is the ',
             b: 'object I want to add',
          }
          arrayOneIndex: 0, 
          arrayTwoIndex: 0
       }
    });

This is my useReducer case-Statement:

case 'ADD_NEW_OBJECT':
            return {
                ...state,
                objectOne: {
                    ...state.objectOne,
                    arrayOne: [
                        ...state.objectOne.arrayOne,
                        {
                            ...state.objectOne.arrayOne[payload.arrayOneIndex],
                            arrayTwo: [
                                ...state.objectOne.arrayOne[payload.arrayOneIndex].arrayTwo,
                                payload.value
                            ]
                        },
                    ]
                }
            }

1 Answers1

0

Immer is a great library for simplifying this code. It generates a deep clone of the object passed to it and then you can mutate the clone.

import produce from "immer";

const reducer = produce((draft, action) => {
  switch (action.type) {
    case ADD_NEW_OBJECT:
      draft.objectOne.arrayOne[action.payload.arrayOneIndex][
        action.payload.arrayTwoIndex
      ].push(value);
      return draft;
  }
});

hackhan
  • 512
  • 3
  • 7
  • Thanks to your answer. I have tried it but I get a TypeError as follows: TypeError: Cannot read property 'push' of undefined –  Jun 30 '20 at 14:49
  • It already fails with draft.objectOne.arrayOne as he can't find it and returns undefined. –  Jun 30 '20 at 14:50
  • are you sure that the array actually exists there? – hackhan Jun 30 '20 at 16:56
  • Yes of course. The structure of the state is like above. –  Jun 30 '20 at 20:36