`I am having an issue with a Quiz I am developing where I am logging the Score count at the end of each game. At the end of the game, I sent a PUT request to update my totalscore in my database.
The potential issues are: I am sending a double request to my database or doubling the score count in my state. As a result, my totalscore values in my database are doubled.
Here is an example of my PUT request from my front-end. This is where I am sending my score value to my user’s table.
Here is an example of my Controller file. There is the logic behind the put request to update my score in my user’s table.
Here are my user table endpoints. updateScore is the endpoint im using.
This is what I see in my console when I tried console logging my totalScore in my controller
console message when console logging totalScore from controller
I tried resetting the state every time the user clicks into the game. I’ve tried storing my score values in a redux store which didnt help.`
2
Answers
Your problem will be on frontend in the React app with the useEffect(). I think it is triggered twice. Check here the best answer: React Hooks: useEffect() is called twice even if an empty array is used as an argument
Without seeing every line of source code it’s a bit hard to troubleshoot.
Some suggestions:
Looks like your useEffect hook is being triggered if either correct or loggedIn changes. Look carefully at when those change, since either changing will cause useEffect to run and update your score. It is more likely that correct changes values twice, but maybe you get it once for loggedIn and once for correct. Could be either depending on how you’ve tested this. If possible, try varying the values you use to test so you can tell which one fired, based on what the score changes to.
In your screenshots you have both updateTotalScore and updateScore methods. Make sure you’re not getting confused with which you’re using when.