Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update object in React state

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:

  1. add a new user { id: 4, name: "Jane" } with id (4) as key
  2. remove a user with id 2
  3. change the name of user #2 to "Peter"

Without any immutable helpers. I'm using Coffeescript and Underscore (so _.extend is ok...).

Thanks.

like image 982
Martin Sojka Avatar asked Apr 15 '16 14:04

Martin Sojka


People also ask

How do you update objects in state React?

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.

How do you update a state object?

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.

How do you update an object in a state array?

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.

How do you update an object in an array in React?

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.


1 Answers

This is what i would do

  • add: var newUsers = _.extend({}, users, { 4: { id: 4, ... } })
  • remove: var newUsers = _.extend({}, users) then delete newUsers['2']
  • change: var newUsers = _.extend({}, users) then newUsers['2'].name = 'Peter'
like image 88
kavun Avatar answered Oct 08 '22 05:10

kavun