I have an indexed list of users
in the JS object (not array). It\'s part of the React state.
{
1: { id: 1, name: \"John\" }
2: { id: 2, name
setState
also accepts a function, which you might find more intuitive
function add( user ) {
this.setState( users => {
users[ user.id ] = user
return users
}
}
function remove( id ) {
this.setState( users => {
delete users[ id ]
return users
}
These functions assume that your state
object is your users
object, if it is actually state.users
then you'd have to pick users
out, passing a function to setState
will always be called passing the actual state
object.
In this example add
can also be used to amend, depending on your actual use-case you may want to create separate helpers.