Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SetState of an array of Objects in React

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
like image 596
Saikat Dey Avatar asked Mar 25 '18 15:03

Saikat Dey


People also ask

How do you update an array of objects in setState 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.

Can useState be an array of objects?

To type the useState hook as an array of objects in React, use the hook's generic, e.g. const [employees, setEmployees] = useState<{salary: number; name: string}[]>([]) . The state variable can be initialized to an empty array and will only accept objects of the specified type.

How do you pass an array of objects in React?

To pass an array as a prop to a component in React, wrap the array in curly braces, e.g. <Books arr={['A', 'B', 'C']} /> . The child component can perform custom logic on the array or use the map() method to render the array's elements.

How do you update state arrays?

Instead, every time you want to update an array, you'll want to pass a new array to your state setting function. To do that, you can create a new array from the original array in your state by calling its non-mutating methods like filter() and map() . Then you can set your state to the resulting new array.


2 Answers

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>
  )
}
like image 159
Omar Avatar answered Sep 22 '22 03:09

Omar


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.

like image 38
simka Avatar answered Sep 21 '22 03:09

simka