React-Redux – how to handle nested property implementation for payloads and reducers

The implementation for nested payload objects and reducers is kinda confusing for me – as i cannot see how it should be implemented.

Imagine having some user input in UI that outputs a json like this:

{
 obj1: 'object 1',
 obj2: 'object 2',
 obj3: [{
    nestedObj1: 'nested object 1',
    nestedObj2: 'nested object 1',
    nestedObj3: [{
                deepNestedObj1: 'deep nested obj 1',
                deepNestedObj2: 'deep nested obj 2',
       }],
}

.. and you then have to implement an action creator first og foremost. This is what i imagined an action creator would look like:

export function addItem(obj1, obj2, obj3) {
return {
type:ADD_ITEM,
payload: {
  obj1,
  obj2,
  obj3: [{
    nestedObj1,
    nestedObj2,
    nestedObj3: [{
      deepNestedObj1,
      deepNestedObj2,
    }]
  }]
}}
}

Now my question is: is how the action creator meant to be used when working with deep nested json objects?

Answer

I would strongly recommend against writing an action creator that way. Per our Redux Style Guide docs page, you should:

Also, you should really be using our official Redux Toolkit package, which will greatly simplify your Redux logic.

I would recommend writing this along the lines of:

const itemsSlice = createSlice({
  name: "items",
  initialState,
  reducers: {
    itemAdded(state, action) {
      const {id1, id2, value} = action.payload;
      if (state[id1]) {
        state[id1][id2].push(value);
      }
    }

  }
})

So, keep the actions as minimal as possible – they should have enough info to describe what happened, and let the reducer figure out how the state should be updated in response.