SetState of an array of Objects in React

to update state constructed like this you will have to find index of element you want to update, copy the array and change found index.

it's easier and more readable if you keep list of records as object, with id as a key and record as a value.


answered March 25 2018

This is how you would use setState and prevstate to update a certain attribute of an object in your data structure.

this.setState(prevState => ({
    itemList: prevState.itemList.map(
    obj => (obj._id === 1234 ? Object.assign(obj, { description: "New Description" }) : obj)
  )
}));

answered Dec 12 2019 (REACT HOOKS)

import React, { useState } from 'react';
const App = () => {
  const [data, setData] = useState([
    {
      username: '141451',
      password: 'password',
      favoriteFood: 'pizza',
    },
    {
      username: '15151',
      password: '91jf7jn38f8jn3',
      favoriteFood: 'beans'
    }
  ]);
  return (
    <div>
    {data.map(user => {
      return (
        <div onClick={() => {
          setData([...data].map(object => {
            if(object.username === user.username) {
              return {
                ...object,
                favoriteFood: 'Potatos',
                someNewRandomAttribute: 'X'
              }
            }
            else return object;
          }))
        }}>
        {JSON.stringify(user) + '\n'}
        </div>
      )
    })}
    </div>
  )
}