2

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!

1 Answer 1

4

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
    })

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.