Reputation: 1127
I have struggle to understand how to update React state -> $push and $unshift..
My state looks like: data = { 2: [1, 2, 3], 7: [5, 3, 4] }
And I need to update records specific object key with variable and delete or add element into that array.. I've tried something like:
var elem_id = this.props.elem_id;
var newArray = update(data, {elem_id: {$push: [4]}});
var newArray = update(data, {elem_id: {$unshift: [4]}});
But unsuccessfully what I'm doing wrong?
Thanks
Upvotes: 1
Views: 346
Reputation: 159105
var newArray = update(data, {elem_id: {$push: [4]}});
will try to push 4
onto an array at the literal key elem_id
; that is to say, elem_id
is an object literal key, and is not replaced with the contents of the variable elem_id
.
If you're using a transpiler that supports ES6's computed property syntax (like Babel), you could do the following:
var newArray = update(data, {[elem_id]: {$push: [4]}});
If you're not, you'll have to create the object and then set the operation:
var toUpdate = {};
toUpdate[elem_id] = {$push: [4]};
var newArray = update(data, toUpdate);
Upvotes: 1