简体   繁体   中英

How to change update an object within a useState array

Suppose we have an array of objects in userInformation:

[
 {
  firstName:'Bob',
  lastName:'Dude',
 },
 {
  firstName:'John',
  lastName:'Rad',
 }
]
  const [userInformation, setUserInformation] = useState([]);

   userInformation.forEach((user, index) => {
      if (snapshot.val().leadID === user.leadID) {
        setUserInformation((userInformation) => ({
          ...userInformation,
          [index]: snapshot.val(),
        }));
      }
    });

I would like to update the second object.

My code doesn't seem to be working quite right. Any suggestions?

Here I think a simple find() would do the trick, rather than trying to loop the array.

const updateInfo = (id, obj /* snapshot.val() */) => {
   const item = userInformation.find(({ leadID }) => leadID === id);
   const updatedItem = {
      ...item,
      ...obj
   };
   
   setUserInformation((previousInfo) => {
      ...userInformation,
      ...updatedItem 
   })
}

Yes few suggestions I have for you:)

First of all you have never assigned userinformation to your state. So it should be some what like below

const [userInformation, setUserInformation] = useState(userinformation);

Or you must be getting userinformation from an API and using useEffect to initialize it.

Second thing is you must have an id as well as index key on each user something like this:

[
 {
  leadId:1,
  firstName:'Bob',
  lastName:'Dude',
  index:1
 },
 {
  leadId:2,
  firstName:'John',
  lastName:'Rad',
  index:2
 }
]

Now, Coming to what you are expecting you can use map() function in such as way that once the condition is met, you update that particular user , otherwise you should return back same users when condition is not met.

 const updatedUsers = userInformation.map((user, index) => {
   if (snapshot.val().leadID === user.leadID) {
     return setUserInformation((userInformation) => ({
        ...userInformation,
      [index]: snapshot.val(),
     }));
   }
    return userInformation;
 });

Sorry for the lack of information provided in my question.

I was using firebase realtime with React, and not wrapping my logic in a useEffect was one problem.

I went with this solution:

  setUserInformation(
        userInformation.map((user) =>
          user.leadID === snapshot.val().leadID
            ? {
                ...user,
                ...snapshot.val(),
              }
            : user
        )
      );

Thank you for all your answers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM