Dynamically set(ting)State in React

So far in React, we’ve known exactly what state we’re setting. But if we don’t know up-front, i.e. we want to dynamically set the state based on some parameter, we can use something called computed property names to “interpolate” the key that we want to change.

In our Pokemania React port, we started with the following code:

But this code is quite stinky. We can refactor this using computed property names.

But wait, this doesn’t work. We’ll get the following error:

The problem is in line three. Since we’re both setting the key dynamically and using the ES6 array spread operator, …self.state.roster will break because that doesn’t exist. So what can we do? Abstraction! If we abstract the array that gets passed into the spread operator, we can dynamically set that as well, then BOOM! Dynamic State Setting!