Tell us what’s happening:
Hi everyone! So I’m currently stuck with the JS Calculator Project #4 and I’m making it in React using Hooks. I am almost finished to it but User Story #9 is bugging out since I can’t think out what’s wrong with the code I implemented.
Your code so far:
Challenge: Javascript Calculator
Link to the Challenge: https://www.freecodecamp.org/learn/front-end-libraries/front-end-libraries-projects/build-a-javascript-calculator
User Story #9: In any order, I should be able to add, subtract, multiply and divide a chain of numbers of any length, and when I hit “=”, the correct result should be shown in the element with the id of “display” (i.e. 3 + 5 * 6 - 2 / 4 -> formula / immediate execution)
The way that this is implemented is that, if I clicked 3 + 5
then clicking x
would evaluate the answer to 8 and then it would show up to the code above together as 8 *
awaiting for the next input but what happens is:
I’ll put also here the functions related to that scenario:
const addOperation = (event) => {
const currentOperation = event.target.value;
setOperation(currentOperation);
if (current === "") return;
if (equation !== "") {
console.log("is this running???");
evaluation();
console.log(current, "is it changed?");
}
setEquation(current + " " + currentOperation);
setCurrent("");
};
const evaluation = () => {
const prev = parseFloat(equation);
const curr = parseFloat(current);
if (isNaN(prev) || isNaN(curr)) return;
const computation = math.evaluate(prev + operation + curr).toString();
setCurrent(computation);
console.log(
prev,
operation,
curr,
"=",
computation,
"should equal to",
current
);
setOperation(undefined);
setEquation("");
};
As you can see from the console.log()
that I created which is included also in the screenshot, the 3 + 5
is evaluated to 8
which is on the computation
variable (I used mathjs
here to evaluate the formula to avoid the eval()
error from React/Javascript since I was using VSC first before implementing it to Codepen) but when I now set my current
value using the hook setCurrent(computation)
the value is still 5 and not 8.
Also, if you tried it normally like a simple 123 + 456 and hitting equal button would give off the right answer which pretty much says that current
gets updated.
Any possible suggestions why the setCurrent
does not get updated? Am I missing something? Thank you!
Edit: Fix code snippet and added notes.