简体   繁体   中英

How to add a deeply nested object to a deeply nested Array in a React Reducer?

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
                            ]
                        },
                    ]
                }
            }

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;
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM