#Adding to object (which is in array) inside setState

1 messages · Page 1 of 1 (latest)

umbral dagger
#

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

clear mangoBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

clear anvil
#

What's quizIndex?

#

You should log prev too

umbral dagger
clear anvil
#

Can you paste the full function?

umbral dagger
#
  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)

clear anvil
#

where does quizIndex come from?

#

const recordAnswers = (answer:any, quizIndex: number) => {

You should do this

umbral dagger
#

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

clear anvil
#

And does console.log(prev) say [{"62": [Object]}]?

umbral dagger
#

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