SetState of an array of Objects in React

Saikat Dey picture Saikat Dey · Mar 25, 2018 · Viewed 30.1k times · Source

Ok, so I'm so frustrated finding the right solution so I'm posting the problem here. Giving an answer would help me a lot, coz I'm stuck!

the state tree looks like this

this.state = {
      itemList : [{
                    _id : 1234,
                   description : 'This the description',
                   amount : 100
                    }, {
                    _id : 1234,
                   description : 'This the description',
                   amount : 100
                    }],
     }

The problems are :

  1. can not update any specific key in the Object of the array according to the _id
  2. The previous state should remain intact

Answer

Omar picture Omar · Mar 25, 2018

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>
  )
}