Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Update deeply nested array of objects using redux toolkit reducer

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading