Reputation: 6914
Started learning react but made my state as an array. my state was not getting properly update when i did something like
this.setState(state => [newItem, ...this.state])
above statement was converting an array to integer indexed object
I was getting a warning
index.js:2178 Warning: App.state: must be set to an object or null
seems like there is some check in react-dom code like this
if (state && (typeof state !== 'object' || isArray(state))) {
why is this happening
what are the issues i can face if i use the state as an array or something else than object or null
Upvotes: -1
Views: 637
Reputation: 2407
setState
accepts objects, plain and simple. If you call this.setState(['a','b'])
it will convert your array to an array-like object. Why? Because React allows that elsewhere in your code you should be able to call this.setState({data: 'something'})
without having that fail. For reference this.state
would now look like this:
{
0: 'a',
1: 'b',
data: 'something'
}
Why did you get a warning? Because React performed this conversion, from array to array-like object, behind the scenes, and wants to let you know that things have changed. For example, after setting state to an array, you won't be able to call this.state.map ...
or any other array methods.
If you need to store an array in state, set it to an object property: this.setState({arrayData: ['a', 'b']})
. In general it's a good practice to wrap your data in object properties, because you will certainly be lifting state up as you develop your application.
Upvotes: 2