Reputation: 1169
I'm trying out immutable.js in my new React project, but I'm having a blackout at adding a Map to an existing List of Maps in my state.
I would previously have written (using Arrays and Objects):
this.setState({
objectsArray: [...this.state.objectsArray, newObject];
})
But I'm struggling to find the proper equivalent with immutable.js. I've tried things along the lines of this, but with no success:
state.get('mapsList').merge(newMap);
I'm finding plenty of examples on the web merging Lists and merging Maps, but I'm having a List of Maps, and the official docs on immutable Lists are not exactly elaborate.
Links to resources and best practices regarding React/Redux state operations appreciated as well, thank you!
Upvotes: 0
Views: 529
Reputation: 1075875
Your "old" code creates a new array with the same objects that already existed, plus a new object.
As far as I can see, Immutable's List#push
does the same thing:
push()
Returns a new
List
with the providedvalues
appended, starting at thisList
'ssize
.push(...values: Array<T>): List<T>
So:
this.setState(({mapsList}) => {
return {mapsList: mapsList.push(newMap)};
});
Side note: I'm using the callback version of setState
because you're not allowed to do what your old code did. If you're setting new state based on existing state, you must use the callback; details.
Upvotes: 1
Reputation: 2620
you need to update the list with
state = state.updateIn(['mapsList'], function(list) { return list.push(newMap); })
that will update the mapsList List with the new newMap
Upvotes: 1