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

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of React-Redux – how to handle nested property implementation for payloads and reducers without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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.

We are here to answer your question about React-Redux – how to handle nested property implementation for payloads and reducers - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji