David
David

Reputation: 569

React set state variable

I've an confusion. I'm trying to add array variable in setState. My code is working properly but wanted to confirm some doubt before committing my code.

Which is right way to store array in state variable ?

var names = ['Jake', 'Jon', 'Thruster'];

this.setState({
    state: names
});

Or

this.setState((state) => {
    state.items.push(names[0]);
    return state;
});

What is necessary of return statement here ?

Can some one please explain me the difference here ? I searched in google but I'm still confused.

Upvotes: 1

Views: 7222

Answers (2)

kosiakMD
kosiakMD

Reputation: 1062

var names = ['Jake', 'Jon', 'Thruster'];

this.setState({
    names //according to Airbnb rules
});

or

this.setState({
    names: names
});


this.state.names = ['Jake', 'Jon', 'Thruster'];

setState takes a second argument - callback, that will called after setting State properties

setState({property1: value1, ...}, () => { //some code after State changed })

Upvotes: 1

Spencer Bigum
Spencer Bigum

Reputation: 1931

The first approach is much more common and in my opinion, easier to read. The issue with your code is you don't need to use the key state, because the function you are calling is "setting state". The key should be something like firstNames.

this.setState({
    firstNames: names
});

You could also just pass the object in the function like this because setState takes an object as a parameter.

var namesObject = { firstNames: names }

this.setState(namesObject);

I would read more about it here and keep doing small tutorials on this an you'll get the hang of it. https://facebook.github.io/react/docs/react-component.html#setstate

Upvotes: 0

Related Questions