Home > Blockchain >  How do I get the correct score in ReactJs?
How do I get the correct score in ReactJs?

Time:07-06

I am making a trivia app in React. Right now, my userScore is always showing 0. However, when I use console.log, I get the correct number of answers that I picked. On the quiz page, I get the percentage of the answers correct. So, I have 7 questions for the trivia. I want my questions to be divided by the length of the questions and multiply by 100 so I can get the percentage of questions answered correctly as the score.

I have the useState here

      const [scoreAfterQuiz, setScoreAfterQuiz] = useState(0);

I convert the score here.

    const handleScore = () => {
      let s = 0
      for(let i = 0; i < questions.length; i  ){
        if(questions[i].answer == myAnswers[i]){
         // const newScore = score   1
        // setScore(newScore)
         s  
        }
      }

      setScoreAfterQuiz(Math.round(((s*10)/questions.length)*10))

      console.log(questions)
      console.log(myAnswers)
      console.log(s) // how many questions I got right
    }

I'm submitting the score through a handler after the submit button is clicked on:

const handleSubmitScoreAndName = (event) => {
  event.preventDefault();
  handleChange(event);
  handleScore(event);
  handleSubmit(event);
  setDisplayName(event.target.value);
  const scoreResult = handleScore(); // responsible only for calculating score
  setScore(scoreResult) // to view score
  addScore(scoreResult) // to add score to the API
  // displayNameHandler(displayName) // add display name
}

I'm submitting my score here through REST API:

const addScore = () => {
   const newScore = {
    displayName:displayName,
    userScore:scoreAfterQuiz,
    quizId, 
    appUserId:auth.user.appUserId
  };
  console.log(newScore)
  const init = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${auth.user.token}`
    },
    body: JSON.stringify(newScore)
  };

  fetch('http://localhost:8080/api/score', init)
    .then(response => {
      if (response.status === 201 || response.status === 400) {
        return response.json();
      } else {
        return Promise.reject(`Unexpected status code: ${response.status}`);
      }
    })
    .then(data => {
      if (data.scoreId) {

        history.push(`/finalscore`); 
      } else {

        setErrors(data);
      }
    })
    .catch(console.log);
};

Why is my score still being posted as 0 in the API? Here is the console.log:

{displayName: 'james', userScore: 0, quizId: 2, appUserId: 3}

CodePudding user response:

Looks like the state scoreAfterQuiz isn't getting its latest value in the submission payload due to the asynchronous nature of setState. Try returning the computed value in the handleScorefunction as:

  const handleScore = () => {
      let s = 0
      for(let i = 0; i < questions.length; i  ){
        if(questions[i].answer == myAnswers[i]){
         s  
        }
      }

      setScoreAfterQuiz(Math.round(((s*10)/questions.length)*10));
      return s
    }

During submission in addScore,get the value using handleScore function as:

const addScore = () => {
   const finalScore = handleScore()
   const newScore = {
    displayName:displayName,
    userScore:finalScore,
    quizId, 
    appUserId:auth.user.appUserId
  };
  console.log(newScore)
  const init = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${auth.user.token}`
    },
    body: JSON.stringify(newScore)
  }}
  • Related