1

I have a state variable that stores an object which contains the array invitees as a value:

const [values, setValues] = useState({
    date: '',
    location: '',
    invitees: []
})

I have an array containing multiple objects:

users = [
    { _id: 'id1', name: 'name1', email: 'email1' },
    { _id: 'id2', name: 'name2', email: 'email2' },
    { _id: 'id3', name: 'name3', email: 'email3' }
]

I'd like to be able to push each of these objects into the values.invitees array.

I can do this for individual objects using a function like this:

const addInvitee = (user) => {
    setValues({ ...values, invitees: [...values.invitees, user] })
}

But my problem is when I try to add multiple objects at once.

I have tried mapping through them like this:

users.map((user) => {
    addInvitee(user)
})

And also using a for loop:

for (let i = 0; i < users; i++) {
    addInvitee(users[i])
}

However both these attempts result in only the last object element in the array being added.

Is anyone able to help me understand why this is happening and what I can do to fix it. Many thanks.

2
  • reactjs.org/docs/… Commented Sep 17, 2022 at 17:56
  • setValues({ ...values, invitees: [...values.invitees, ...users] }) Commented Sep 17, 2022 at 18:01

1 Answer 1

3

Problem

That is because values reffered inside the addInvitee is the same initial values (empty array) not the updated values.

const addInvitee = (user) => {
    setValues({ ...values, invitees: [...values.invitees, user] })
}

Solution

To avoid the stale value issue you should use the callback function of setter of the useState hook.

Try like below:

const addInvitee = (user) => {
  setValues((prevValues) => ({
    ...prevValues,
    invitees: [...prevValues.invitees, user]
  }));
};

In this case, prevValues is always guaranteed to be the updated values.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.