I’m trying to complete FreeCodeCamp “Front End Development Libraries” course. One of the final projects there is to build a simple calculator. More details about it can be found here
When I run automated tests to verify that the functionality works as expected, some of them fail (Click on Hamburger menu -> Select JavaScript Calculator -> Run Tests).
For example, when I manually click the formula “5 * 5.5”, it returns 27.5 as expected. However, it’s written in test #12 that the result is 302.5 instead of 27.5.
I realized that it happens because a new test sometimes sums up the result of the previous calculation to the first number of the next test (it calculated “55 * 5.5” instead of “5 * 5.5”). I was trying to debug using console logs and React debugging tools. I believe it’s caused due to the asynchronous useState. useEffect hook is suggested by many tutorials but I’m not sure if I use it in a right way.. I keep formula and output in useState variables like this:
const [formula, setFormula] = useState([]);
const [output, setOutput] = useState("0");
const [reset, setReset] = useState(false);
here is my AC function:
const handleAC = () => {
setFormula([]);
setOutput("0");
setReset(true);
}
And useEffect hook:
useEffect(() => {
if (reset) {
// Perform any operations that should happen after reset
console.log("Reset complete");
console.log("AC clicked: ", formula);
setReset(false);
}
}, [formula, output, reset]);
I have an assumption that the tests run very fast and formula’s value isn’t updated frequent enough. However, I don’t have much experience with React and may be completely wrong… So I pushed the code to Github to share the complete file App.js. And temporary ran the app on Heroku so you could see how it actually works.
I will be happy to share more details if needed and thank you in advance!
I tried to wait for the state to be updated using useEffect hook, callback functions and so on. Also, I spent quite a lot of time by debugging the behavior but didn’t manage to get it working.