4

I'm starting with redux, and I want to do the following modification to my state:

From this:

state = {
  loaded: true,
  fetching false,
  byId: {
    "employeeID1": {
      id: "employeeID1",
      name: "Steve"
     },
    "employeeID2": {
      id: "employeeID2",
      name: "Susan"
     }
  }
}

To this:

{
  loaded: true,
  fetching false,
  byId: {
    "employeeID1": {
      id: "employeeID1",
      name: "Steve",
      data: data  // <---- add a new property

     },
    "employeeID2": {
      id: "employeeID2",
      name: "Susan"
     }
  }
}

This const modifEmployee = {...state.byId["employeeID1"], data: data} will give me the modified employee with the data.

But, how can I add the modified employee in byId while mantaining the others unchanged?

1 Answer 1

3

You could do something like this using spread syntax:

{
  ...state,
  byId: {
    ...state.byId,
    employeeID1: { ...state.byId.employeeID1, data }
  }
}

If "employeeID1" value is a fetched from a variable employeeId, then you could use computed property names:

{
  ...state,
  byId: {
    ...state.byId,
    [employeeId]: { ...state.byId[employeeId], data }
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you!, the second example works perfect in my case. If I've understood correctly, I need to use the spread operator on every "level"
@Ana you're welcome. Also, forgot to mention this. You don't need to do data: data if the variable name and the property name you're adding are the same. That's why just adding data works here. Shorthand property names

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.