ozansozuoz
ozansozuoz

Reputation: 237

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?

Upvotes: 0

Views: 68

Answers (3)

Imran Rafiq Rather
Imran Rafiq Rather

Reputation: 8098

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

Upvotes: 1

ozansozuoz
ozansozuoz

Reputation: 237

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!

Upvotes: 0

Matt D. Webb
Matt D. Webb

Reputation: 3314

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

Upvotes: 1

Related Questions