Roy Z
Roy Z

Reputation: 117

Component not updating on deeply nested redux object

I have a project portion of my app, and users can create events within the project. My redux state is deeply nested, which looks like:

enter image description here

When users create an event, I update state with the following:

case CREATE_PROJECT_TODO:
    const data = [...state.data];
    const index = state.data.findIndex(project => project._id===action.payload.project_id);
    data[index].events = [
        ...data[index].events,
        action.payload  
    ];
    return {
        ...state,
        data
    };

However, my react component isn't updating to reflect the changes. I'm quite sure I'm not mutating state. Is it an issue with deeply nested objects, and react can't detect those changes! Any help would be appreciated!

Upvotes: 2

Views: 1251

Answers (1)

gdh
gdh

Reputation: 13692

With const data = [...state.data], you are doing a shallow copy.

Use map and update your state. Your state is updated correctly and will trigger the component re-render properly.

case CREATE_PROJECT_TODO:
    const index = state.data.findIndex((project) => project._id === action.payload.project_id)
    const updatedData = state.data.map((item, idx) => {
    if (idx === index) {
        return {
        ...item,
        events: [...item.events, action.payload],
        }
    }
    return item
    })

Upvotes: 4

Related Questions