SetState of an array of Objects in React SetState of an array of Objects in React reactjs reactjs

SetState of an array of Objects in React


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


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.


The only way to do this will be to copy itemList, modify it, and set the state to it.

update() {   let itemList = this.state.itemList.slice();   //update it   this.setState({ itemList });}