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

Call variable from string value with React Redux

Still learning React, having trouble finding the solution on this one.

I have a series of arrays in the initialState of a redux slice, i.e

const initialState = {
   sprites: {
      one: [1, 2, 3],
      two: [4, 5, 6],
      three: [7, 8, 9]
   }
}

In the app, when the user clicks on a particular button, among other things, I need to get the length of the relevant array.

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

Here’s an example of the app:

<Component onClick={() => {dispatch(checkArray("one"))}/>

And the reducer:

checkArray: (state, {payload}) => {
   var arrayLength = state.sprites.{payload}.length;
   console.log(arrayLength);
}

Obviously this does not yield the desired effect. Using {payload} just throws an error. But how do I convert the payload in a way that will yield the numerical value of the length of the state.sprites.one.length array?

Thanks

>Solution :

Use bracket notation.

state.sprites[payload].length;
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