Adding to object (which is in array) inside setState
Unanswered
Virginia's Warbler posted this in #help-forum
Virginia's WarblerOP
My code is
So the object is being overwritten instead of being added to.
I want it to be added to. Please help me regarding how to achieve that
setAnswers(prev => {
let answers = [...prev];
if (typeof answers[quizIndex] === 'undefined') {
answers[quizIndex] = {[userProfile.id]: answer};
}
else {
let opponentsAnswer = answers[quizIndex];
answers[quizIndex] = {...opponentsAnswer, [userProfile.id]: answer}; // Overwrites instead of adding to object
}
console.log({answers});
// LOG {"answers": [{"62": [Object]}]}
// LOG {"answers": [{"31": [Object]}]}
return answers;
});
answers
is an array of objects: [{userId1: answer, userId2: answer}, {userId1: answer, userId2: answer}, ]
So the object is being overwritten instead of being added to.
I want it to be added to. Please help me regarding how to achieve that
16 Replies
American
What's quizIndex?
You should log prev too
@American You should log prev too
Virginia's WarblerOP
its just a number, incrementing from 0 to whatever
American
Can you paste the full function?
Virginia's WarblerOP
const recordAnswers = (answer:any) => {
setAnswers(prev => {
let answers = [...prev];
if (typeof answers[quizIndex] === 'undefined') {
answers[quizIndex] = {[userProfile.id]: answer};
}
else {
let opponentsAnswer = answers[quizIndex];
answers[quizIndex] = {...opponentsAnswer, [userProfile.id]: answer}; // Todo: Solve: Overwrites instead of adding to object
}
console.log({answers});
// LOG {"answers": [{"62": [Object]}]}
// LOG {"answers": [{"31": [Object]}]}
return answers;
});
};
That's actually the function
recordAnswers
is called from 2 places. If the user himself answers; and when opponent answers (updated from Websocket)American
where does quizIndex come from?
const recordAnswers = (answer:any, quizIndex: number) => {
You should do this
Virginia's WarblerOP
I dont think
quizIndex
is the problem. As of now, I am just testing it with quizIndex
always being 0It is the object in
answers[quizIndex]
that's kept being overwritten, instead of being added toI want
answers
to be [{"62": [Object], "31": [Object]}]
, instead of being just [{"31": [Object]}]
American
And does console.log(prev) say
[{"62": [Object]}]
?Virginia's WarblerOP
Oops, silly mistake. As it turned out, I used 31 for both user Ids
The
was from a earlier log
The
// LOG {"answers": [{"62": [Object]}]}
// LOG {"answers": [{"31": [Object]}]}
was from a earlier log
Thank you
American
You're welcome