whats the best way to update an object in an array in reactjs?

  • Last Update :
  • Techknowledgy :

First, find the index of the element you're replacing in the state array. Second, update the element at that index You can do this with multiple way, I am going to show you that I mostly used. When I am working with arrays in react usually I pass a custom attribute with current index value, in the example below I have passed data-index attribute, data- is html 5 convention. If you have an array as part of your state, and that array contains objects, whats an easy way to update the state with a change to one of those objects?

This is our Splunktool team suggestion ✌, we tried and its working fine
const initialState = [{
      name: "foo",
      counter: 0
   },
   {
      name: "far",
      counter: 0
   },
   {
      name: "faz",
      counter: 0
   }
];​
const [state, setState] = useState(initialState);​
const clickButton = () => {
   // 1. Make a shallow copy of the array
   let temp_state = [...state];

   // 2. Make a shallow copy of the element you want to mutate
   let temp_element = {
      ...temp_state[0]
   };

   // 3. Update the property you're interested in
   temp_element.counter = temp_element.counter + 1;

   // 4. Put it back into our array. N.B. we *are* mutating the array here, but that's why we made a copy first
   temp_state[0] = temp_element;

   // 5. Set the state to our new copy
   setState(temp_state);
}

I quite like doing this with Object.assign rather than the immutability helpers.

handleCommentEdit: function(id, text) {
   this.setState({
      data: this.state.data.map(el => (el.id === id ? Object.assign({}, el, {
         text
      }) : el))
   });
}

I just think this is much more succinct than splice and doesn't require knowing an index or explicitly handling the not found case.

If you are feeling all ES2018, you can also do this with spread instead of Object.assign

this.setState({
   data: this.state.data.map(el => (el.id === id ? {
      ...el,
      text
   } : el))
});

Suggestion : 2

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. We can use the Array.filter method to remove an object from a state array in React. To update an array of objects state in React: On each iteration, we check if the id of the object is equal to 2, and if it is, we update its name and country properties.

1._
Copied!import {useState} from 'react';

export default function App() {
  const initialState = [
    {id: 1, name: 'Alice', country: 'Austria'},
    {id: 2, name: 'Bob', country: 'Belgium'},
  ];

  const [employees, setEmployees] = useState(initialState);

  // ✅ Add an object to a state array
  const addObjectToArray = obj => {
    setEmployees(current => [...current, obj]);
  };

  // ✅ Update one or more objects in a state array
  const updateObjectInArray = () => {
    setEmployees(current =>
      current.map(obj => {
        if (obj.id === 2) {
          return {...obj, name: 'Sophia', country: 'Sweden'};
        }

        return obj;
      }),
    );
  };

  // ✅ Remove one or more objects from state array
  const removeObjectFromArray = () => {
    setEmployees(current =>
      current.filter(obj => {
        return obj.id !== 2;
      }),
    );
  };

  return (
    <div>
      <button
        onClick={() =>
          addObjectToArray({
            id: Math.random(),
            name: 'Carl',
            country: 'Canada',
          })
        }
      >
        Add employee
      </button>

      <button onClick={updateObjectInArray}>Update object in array</button>

      <button onClick={removeObjectFromArray}>Remove object from array</button>

      {employees.map(employee => {
        return (
          <div key={employee.id}>
            <h2>name: {employee.name}</h2>
            <h2>country: {employee.country}</h2>

            <hr />
          </div>
        );
      })}
    </div>
  );
}
2._
Copied!
   const addObjectToArray = obj => {
      setEmployees(current => [...current, obj]);
   };

addObjectToArray({
   id: 3,
   name: 'Carl',
   country: 'Canada',
})
3._
Copied!
   const updateObjectInArray = () => {
      setEmployees(current =>
         current.map(obj => {
            if (obj.id === 2) {
               return {
                  ...obj,
                  name: 'Sophia',
                  country: 'Sweden'
               };
            }

            return obj;
         }),
      );
   };

Suggestion : 3

Arrays are mutable in JavaScript, but you should treat them as immutable when you store them in state. Just like with objects, when you want to update an array stored in state, you need to create a new one (or make a copy of an existing one), and then set state to use the new array. Instead, create a new array which contains the existing items and a new item at the end. There are multiple ways to do this, but the easiest one is to use the ... array spread syntax: In general, you should only mutate objects that you have just created. If you were inserting a new artwork, you could mutate it, but if you’re dealing with something that’s already in state, you need to make a copy.

1._
import { useState } from 'react';

let nextId = 0;

export default function List() {
  const [name, setName] = useState('');
  const [artists, setArtists] = useState([]);

  return (
    <>
      <h1>Inspiring sculptors:</h1>
      <input
        value={name}
        onChange={e => setName(e.target.value)}
      />
      <button onClick={() => {
        setName('');
        artists.push({
          id: nextId++,
          name: name,
        });
      }}>Add</button>
      <ul>
        {artists.map(artist => (
          <li key={artist.id}>{artist.name}</li>
        ))}
      </ul>
    </>
  );
}

2._
setArtists( // Replace the state  [ // with a new array    ...artists, // that contains all the old items    { id: nextId++, name: name } // and one new item at the end  ]);
3._
import { useState } from 'react';

let nextId = 0;

export default function List() {
  const [name, setName] = useState('');
  const [artists, setArtists] = useState([]);

  return (
    <>
      <h1>Inspiring sculptors:</h1>
      <input
        value={name}
        onChange={e => setName(e.target.value)}
      />
      <button onClick={() => {
        setName('');
        setArtists([
          ...artists,
          { id: nextId++, name: name }
        ]);
      }}>Add</button>
      <ul>
        {artists.map(artist => (
          <li key={artist.id}>{artist.name}</li>
        ))}
      </ul>
    </>
  );
}

5._
import { useState } from 'react';

let initialArtists = [
  { id: 0, name: 'Marta Colvin Andrade' },
  { id: 1, name: 'Lamidi Olonade Fakeye'},
  { id: 2, name: 'Louise Nevelson'},
];

export default function List() {
  const [artists, setArtists] = useState(
    initialArtists
  );

  return (
    <>
      <h1>Inspiring sculptors:</h1>
      <ul>
        {artists.map(artist => (
          <li key={artist.id}>
            {artist.name}{' '}
            <button onClick={() => {
              setArtists(
                artists.filter(a =>
                  a.id !== artist.id
                )
              );
            }}>
              Delete
            </button>
          </li>
        ))}
      </ul>
    </>
  );
}

6._
setArtists(artists.filter(a => a.id !== artist.id));

Suggestion : 4

If we want to use arrays or objects in our React state, we have to create a copy of the value before modifying it. This is a cheat sheet on how to do add, remove, and update items in an array or object within the context of managing React state. Just wrote How to update an array of objects in React state We can also use the spread operator to create copy and append an item with the following syntax: Edit: Thanks for this cheatsheet, nice to have it open when fighting with array states.

1._
const [todos, setTodos] = useState([]);
2._
const handleAdd = (todo) => {
   const newTodos = todos.slice();
   newTodos.push(todo);
   setTodos(newTodos);
}
3._
const handleAdd = (todo) => {
   const newTodos = [...todos];
   newTodos.push(todo);
   setTodos(newTodos);
}
5._
const handleRemove = (todo) => {
   const newTodos = todos.filter((t) => t !== todo);
   setTodos(newTodos);
}
6._
const handleUpdate = (index, todo) => {
   const newTodos = [...todos];
   newTodos[index] = todo;
   setTodos(newTodos);
}

Suggestion : 5

Good point. But my point is when you want to update array state, don't act on the array state directly, you need to create another array from the state array and there are multiple solutions for that, I chose destructuring. that's all. Ever tried to update object or array state directly in React? I did that, the state of my component didn't change. Destructuring the object/array was the solution. Your Array example is not updating state as you intended due to poor nomenclature. If you have to spread you can just setState(value => [ ...value, someNewValue ]);, which IMO is better served by setState(value => value.concat(someNewValue)); where the latter is using array semantics not iterator semantics.

1._
import React, { useState } from 'react';

const States = () => {

  const [objectValue, setObjectValue] = useState({});

  const updateObjectValue = (key, value) => {
    // Destructure current state object
    const objectvalue = {
      ...objectValue,
      [key]: value,
    };
    setObjectValue(objectvalue);
  };

  return <Component/>;

};

export default States;
2._
import React, { useState } from 'react';

const States = () => {

  const [arrayValue, setArrayValue] = useState([]);

  const updateArrayValue = (value) => {
    // Destructure current state array
    const arrayvalue = [ ...arrayValue ];
    arrayvalue.push(value);
    setArrayValue(arrayvalue);
  };

  return <Component/>;

};

export default States;

Suggestion : 6

We simply, use the update method (In our example it's setMyArray()) to update the state with a new array that's created by combining the old array with the new element using JavaScript' Spread operator. You can't update the array directly without using the method returned from useState(). In our case, it's setMyArray(). We can also define a function that creates the new array from the old array and pass it to the useState update method.

1._
import React from "react";

const {
   useState
} = React;

const [myArray, setMyArray] = useState([]);
2._
myArray.push(1);
3._
setMyArray(oldArray => [...oldArray, newElement]);

Suggestion : 7

How we will render an Array of Objects?We will use the map function to access each object from the array.The map() method in JavaScript creates an array by calling a specific function on each element present in the parent array. It is a non-mutating method. Generally, map() method is used to iterate over an array and calling function on every element of the array.Syntax: index: It is an optional parameter, and it holds the index of the current element. React.js is a declarative, efficient, and flexible JavaScript library for building user interfaces. It’s ‘V’ in MVC. ReactJS is an open-source, component-based front-end library responsible only for the view layer of the application. It is maintained by Facebook.In this article, we will learn about How to render an array of objects in React.

Initially, we will begin with learning what is an array of objects.
 Array of objects: It stores multiple values in a single variable. The object can contain anything in the real world, such as person names, cars, game characters. Objects are very easy to use in some situations, if you know where the data is being processed. The character set of objects are known as Properties. Properties of an object can be called by using DOT(“.”) notation and (“[]”) notation.
Syntax:

var object = [{
   "property1": "value1",
   "property2": "value2"
}]

Now,  let’s create a React application to learn How to render an array of objects.
Creating React Application:

Step 1: Create a React application using the following command.

npx create - react - app foldername

Step 2: Once it is done, change your directory to the newly created application using the following command.

cd foldername

Return Value: It returns a new array and elements of arrays are the result of callback function.

Example 1: In this example, we will simply create an array of objects that contains states and their capitals. We will render them in an unordered list. States are in red and bold.

import React from 'react'
function RenderingArrayOfObjects() {
    const data = [
        {
            "State": "Uttar Pradesh",
            "Capital": "Lucknow"
        },
        {
            "State": "Gujarat",
            "Capital": "Gandhinagar"
        },
        {
            "State": "Karnataka",
            "Capital": "Bengaluru"
        },
        {
            "State": "Punjab",
            "Capital": "Chandigarh"
        },
        {
            "State": "Maharashtra",
            "Capital": "Mumbai"
        }
    ]
    const listItems = data.map(
        (element) => {
            return (
                <ul type="disc">
                    <li style={{ 
                        fontWeight: 'bold', 
                        color: 'red' }}
                    >
                        {element.State}
                    </li>
                    <li>{element.Capital}</li>
                </ul>
            )
        }
    )
    return (
        <div>
            {listItems}
        </div>
    )
}
function App() {
    return (
        <div className="App">
            <div>
                <h1 style={{ color: 'green' }}>
                    Pretagcode
                </h1>
                <h3>Rendering Array of Objects</h3>
                <br></br>
                <RenderingArrayOfObjects />
            </div>
        </div>
    );
}
  
export default App;

Example 2: In this example, we will map an Array of Object containing student Marks into a Table.

Note: To run below example, you need to install react-bootstrap and bootstrap.

npm install react - bootstrap bootstrap @5 .1 .3 bootstrap