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.
CodePudding user response:
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.