Home > Mobile >  Can I change the value of a property inside a redux state using a value passed in during the action
Can I change the value of a property inside a redux state using a value passed in during the action

Time:07-08

I am trying to change the redux state, which is an object, but the property of the object that needs to be changed depends upon what the user wants to change. The state has properties in it that represent different rows in a table, and since there are a lot, I cant have a specific case for each one. So for example, instead of saying I want to change row1, I want to change action.row.

Here's some code of how it would be normally:

case 'CHANGE_STATE': {
      return {
        ...state, row1: action.payload
      }
    }

And here's an example of how I want it to work

case 'CHANGE_STATE': {
      return {
        ...state, action.row: action.payload
      }
    }

Where action.row is provided when calling the redux action.

CodePudding user response:

You can use variables as object keys using a bracket notation:

{
  ...state, [action.row]: action.payload
}
  • Related