Irfan
Irfan

Reputation: 81

Javascript, ReactJs setState not working

I am learning react and I have this tutorial online quiz-react, so i try to make few adjustment, I want user to click on HellYa it will increment for example answers type - "Brown" "D" "JP" each by +1, this is my quizQuestion.js

{
 question: "I am task oriented in order to achieve certain goals",
 answers: [
  {
    type: "Brown,D,JP",
    content: "Hell Ya!"
  },
  {
    type: " ",
    content: "Nah"
  }
 ]
},

My Constructor for init state is as follow

this.state = {
  counter: 0,
  questionId: 1,
  question: '',
  answerOptions: [],
  answer: '',
  answersCount: {
    Green: 0,
    Brown: 0,
    Blue: 0,
    Red: 0,
    A: 0,
    B: 0,
    C: 0,
    D: 0,
    EI: 0,
    SN: 0,
    TF: 0,
    JP: 0
  },
  result: ''
};

and following the tutorial, i am using react-addons-update for updating the answerCount and answer, here is my function

setUserAnswer(answer) {
 if (answer.trim()) {
   const answer_array = answer.split(',');
   let updatedAnswersCount = null;
   answer_array.forEach((answer) => {
     updatedAnswersCount = update(this.state.answersCount, {
      [answer]: {$apply: (currentValue) => currentValue + 1}
    });
  }, this);
  this.setState({
    answersCount: updatedAnswersCount,
    answer: answer
  });
 }
}

But after several attempts i still cannot figure out how to individually increment answer type by 1, right now it only update JP +1 for example but it does not update Brown and D, what should i do? thanks

Upvotes: 0

Views: 72

Answers (2)

It seems it is always using the current state as the base object, so only the last answer inside the foreach will be updated.

Try the following:

setUserAnswer(answer) {
 if (answer.trim()) {
   const answer_array = answer.split(',');
   let answerCountUpdates = update(this.state.answersCount, {$merge: {}}) // copy this.state.answersCount, will search a better way

   answer_array.forEach((answer) => {
     answerCountUpdates = update(answerCountUpdates, {
      [answer]: {$apply: (currentValue) => currentValue + 1}
     });
   }, this);

   updatedAnswersCount = update(this.state.answersCount, {$merge: answerCountUpdates})

   this.setState({
     answersCount: updatedAnswersCount,
     answer: answer
   });
  }
}

Upvotes: 1

T Porter
T Porter

Reputation: 1281

It looks like you've named your forEach()'s iteration object "answer" as well as the parameter passed in to setUserAnswer(). Try changing one of these, as it's probably causing problems.

Upvotes: 0

Related Questions