Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I change the value of a property inside a redux state using a value passed in during the action call by the user?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

>Solution :

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

{
  ...state, [action.row]: action.payload
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading