Home > Software engineering >  Update deeply nested array of objects using redux toolkit reducer
Update deeply nested array of objects using redux toolkit reducer

Time:09-05

I am new in redux. So pardon any silly mistakes.

I have deeply nested array of objects like the below structure:

const initialState = {
    schedules: [
        {
            "id": 1,
            "role_id": 1,
            "rules": [
                {
                    "id": 1,
                    "module_id": 16,
                    "remark_id": 2,
                },
                ...
            ]
        },
        ...
    ]
}

I need to update remark_id inside the rules array inside a schedule object.

I have tried this, but no idea why it is not working:

updateRemark: (state, action) => {
    const { remark_id, rule_id, schedule_id } = action.payload
        const schedule = state.schedules.find(schedule => schedule.id == schedule_id)
        if (schedule) {
            const rule = schedule.rules.find(rule => rule.id == rule_id)
            if (rule) {
                rule.remark_id = remark_id
            }
        }
    }
},

I have followed the guide from official docs: https://redux-toolkit.js.org/usage/immer-reducers#updating-nested-data

CodePudding user response:

I think your code should be:

const index = schedule.rules.findIndex(rule => rule.id == rule_id)
schedule.rules[index].remark_id = remark_id

Whithout the destruction:

const rule = schedule.rules.find(rule => rule.id == rule_id)
  • Related