Search code examples
reduxngrx-store

How to use variable in spread while updating a value of a nested object in a reducer?


My question is just one step ahead of question here

I want to know if there is any way by which I can use variables in place of "Professional" (which is a key in reference question) because my model is of the following type:

const list = {
  categories: {
    1: {
      name: "Golf",
      active: false
    },
    2: {
      name: "Ultimate Frisbee",
      active: false
    }
  }
}

I want to access 1 and 2 i.e. ids in the code below:

return {
  ...state,
  categories: {
    ...state.categories,
    <dynamic_Id>: {
      name:"xyz"
    }
  }
}

My main aim is to update name property of selected id. Please let me know if there is any solution to it. Thanks in advance.


Solution

  • I think this is what you're after

      return {
          ...state,
          categories: {
            ...state.categories,
            [idProp]: {
            ...state.categories[idProp],
              name:"xyz"
            }
          }
        }