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:
Without any immutable helpers. I'm using Coffeescript and Underscore (so _.extend is ok...).
Thanks.
State can hold any kind of JavaScript value, including objects. But you shouldn't change objects that you hold in the React state directly. Instead, when you want to update an object, you need to create a new one (or make a copy of an existing one), and then set the state to use that copy.
To update nested properties in a state object in React: Pass a function to setState to get access to the current state object. Use the spread syntax (...) to create a shallow copy of the object and the nested properties. Override the properties you need to update.
To update an object in a state array, call the map() method to iterate over the array and update the object that matches the condition. Copied! const updateObjectInArray = () => { setEmployees(current => current.
To update an object in an array in React state: Use the map() method to iterate over the array. On each iteration, check if a certain condition is met. Update the object that satisfies the condition and return all other objects as is.
This is what i would do
var newUsers = _.extend({}, users, { 4: { id: 4, ... } })
var newUsers = _.extend({}, users)
then delete newUsers['2']
var newUsers = _.extend({}, users)
then newUsers['2'].name = 'Peter'
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