I'm using reactjs to populate state.users with a new member when he or she signs in.
The following code is working
var users = this.state.users;
users.push(member);
this.setState({users: users});
But when I try to wrap everything in one line of code it fails
this.setState({users: this.users.state.push(member)});
When I try the above I get an error further down in my list.jsx
Uncaught TypeError: this.props.users.map is not a function
Any idea what is causing this? I'm thinking that when I use the one line solution the wrong kind of object is passed into the state?
Thank you!
It happens because .push returns the new length (int number), not array,
var data = {
users: []
};
data.users = data.users.push(10);
console.log(typeof data.users); // number
.push- return the new length property of the object upon which the method was called.
You can use .concat instead of .push
this.setState({
users: this.state.users.concat(member)
});
or
this.setState({
users: [...this.state.users, member]
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With