Next.js Discord

Discord Forum

Adding to object (which is in array) inside setState

Unanswered
Virginia's Warbler posted this in #help-forum
Open in Discord
Avatar
Virginia's WarblerOP
My code is
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

Avatar
American
What's quizIndex?
You should log prev too
Avatar
@American You should log prev too
Avatar
Virginia's WarblerOP
its just a number, incrementing from 0 to whatever
Avatar
American
Can you paste the full function?
Avatar
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)
Avatar
American
where does quizIndex come from?
const recordAnswers = (answer:any, quizIndex: number) => {

You should do this
Avatar
Virginia's WarblerOP
I dont think quizIndex is the problem. As of now, I am just testing it with quizIndex always being 0
It is the object in answers[quizIndex] that's kept being overwritten, instead of being added to
I want answers to be [{"62": [Object], "31": [Object]}], instead of being just [{"31": [Object]}]
Avatar
American
And does console.log(prev) say [{"62": [Object]}]?
Avatar
Virginia's WarblerOP
Oops, silly mistake. As it turned out, I used 31 for both user Ids
The
      // LOG  {"answers": [{"62": [Object]}]}
      // LOG  {"answers": [{"31": [Object]}]}  

was from a earlier log
Thank you
Avatar
American
You're welcome