1

I have an issue with updating the immutable redux and quite nested data. Here's an example of my data structure and what I want to change. If anyone could show me the pattern of accessing this update using ES6 and spread operator I would be thankful.

My whole state is an object with projects (key/value pairs - here as an example only one project) that are objects with its own key (and the keys are ids as well), arrays of procedures and inside the tasks:

{ 1503658959473: 
  { projectName: "Golden Gate",
    projectLocation": "San Francisco",
    start:"22/09/1937",
    id:1503658959473,
    procedures:[
      { title: "Procedure No. 1",
        tasks:[
          {name: "task1", isDone: false},
          {name: "task2", isDone: false},
          {name: "task3", isDone: false}
        ]
      }
    ]
  }
 }

What I'm willing to do is to update one single task 'isDone' property to 'true'. It's some kind of toggling the tasks. How can I return this state with that information updated?

The action creator pass this information to reducer:

export function toggleTask(activeProject, task, taskIndex) {
 return {
    type: TOGGLE_TASK,
    payload: {
        activeProject,
        task,
        taskIndex
    }
 };

}

2 Answers 2

1

You've run into a common issue with Redux. The docs recommend that you flatten your data structure to make it easier to work with, but if that's not what you want to do, I'd refer to this part of their docs.

Because both Object.assign() and the ...spread operator create shallow copies, you must go through each level of nest in your object and re-copy it.

Your code might look something like this...

function updateVeryNestedField(state, action) {
    return {
        ...state,
        procedures : {
            ...state.procedures,
            tasks : {
               return tasks.map((task, index) => {
                 if (index !== action.taskIndex) {
                   return task
                 }
                 return {
                   ...task,
                   task.isDone: !task.isDone 
                 }
               }
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

I myself would create a new class called ProjectModel, which has a public method toggleTask that is able to update its task's status. The reducer state would be an object whose keys are project IDs and values are ProjectModel instances.

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.