Search code examples
javascriptreactjsreduxreact-redux

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.

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;