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: "Jim" }
3: { id: 3, name: "James" }
}
What's the best practice to:
- add a new user { id: 4, name: "Jane" } with id (4) as key
- remove a user with id 2
- change the name of user #2 to "Peter"
Without any immutable helpers. I'm using Coffeescript and Underscore (so _.extend is ok...).
Thanks.
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: "Jim" }
3: { id: 3, name: "James" }
}
What's the best practice to:
- add a new user { id: 4, name: "Jane" } with id (4) as key
- remove a user with id 2
- change the name of user #2 to "Peter"
Without any immutable helpers. I'm using Coffeescript and Underscore (so _.extend is ok...).
Thanks.
Share Improve this question asked Apr 15, 2016 at 14:58 Martin SojkaMartin Sojka 5335 silver badges19 bronze badges5 Answers
Reset to default 9 +50This is what i would do
- add:
var newUsers = _.extend({}, users, { 4: { id: 4, ... } })
- remove:
var newUsers = _.extend({}, users)
thendelete newUsers['2']
- change:
var newUsers = _.extend({}, users)
thennewUsers['2'].name = 'Peter'
If you're not using Flux, you use this.setState() to update the state object.
delUser(id) {
const users = this.state.users;
delete users[id];
this.setState(users);
}
addChangeUser(id, name) {
const users = this.state.users;
users[id] = {id: id, name: name};
this.setState(users);
}
Then you can execute your test cases with this:
addChangeUser(4, 'Jane);
addChangeUser(2, 'Peter');
delUser(2);
Apart from _.extend you can use Map for storing user
let user = new Map();
user.set(4, { id: 4, name: "Jane" }); //adds with id (4) as key
user.myMap.set(2, { id: 2, name: "Peter" }); // set user #2 to "Peter"
user.delete(3); //deletes user with id 3
Using spreads:
Adding
this.setState({
...this.state,
4: { id: 4, name: "Jane" },
}
Removing id 2
let prevState = this.state;
let {"2": id, ...nextState} = prevState;
this.setState({
...nextState,
}
Changing id 2
this.setState({
...this.state,
2: {
...this.state["2"],
name: "Peter",
}
}
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.