split string in javascript, reactjs

Viewed 55443

so I'm developing a quiz application sort of, so this is my initial state of the app when it first launch, I also have quizApplication.js component store all the question and answers,

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

and here is my function to set the user answer

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

I also have a AnswerOption component like so

function AnswerOption(props) {
 return (
   <AnswerOptionLi>
    <Input
     checked={props.answerType === props.answer}
     id={props.answerType}
     value={props.answerType}
     disabled={props.answer}
     onChange={props.onAnswerSelected}
   />
    <Label className="radioCustomLabel" htmlFor={props.answerType}>
     {props.answerContent}
    </Label>
   </AnswerOptionLi>
  );
 }

So what im try to do is that whenever the user click on HellYa! it will increment "Brown" and "D" and "JP" by +1, but right now it gives me a new answersCount value as Brown,D,JP: null, so how should I achieve this? Many thanks!

1 Answers

You have split your type, but havent made use of them yet.

As you have split your type, you would get answer_array with a length of 3 containing ["Brown", "D", "JP"]

const answer_array = answer.split(',');

Next you are updating your state with the updated answer count. You are performing the below

const updatedAnswersCount = update(this.state.answersCount, {
 [answer]: {$apply: (currentValue) => currentValue + 1},
});

Here answer contains "Brown,D,JP". Since you want to update each of it by +1, lets loop over the split value and update it.

let updatedAnswersCount = null;

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

Here, i'm assuming that your type is unique. Meaning Brown/D/JP is present only for this answer and not for anything else. So we are assuming all will have same value.

Related