JavaScript Calculator: continue calculation by pressing operator after = was press

Hi,

My project has passed 14/16 tests. I am working on implementing the “continue calculation by pressing operators after equals sign(=) was pressed” feature.

Question

It seems like whenever I do this.setState({});, the state isn’t updated right the way. Is there a way to get around this or I have to change all my code? If so, can you give me some pointer to learn more about this mechanism, please?

Details

This is the logic I m trying to implement:

  • Set a “lastAnswer” variable in my state whenever users clicked “=”
  • When users clicked another key, check if it’s an operator and if there’s “lastAnswer” was set.
  • Updated the state and continue with my switch statement to handle the users’ input in my function handleClick at Source code’s line 199 - 245.
handleClick(e){
    let input=e.target.textContent;
    //continue calculation
    if(this.state.lastAnswer && ["+","-","*","/"].includes(input)){
      console.log("Continue!");
      this.setState({
        display: this.state.lastAnswer,
        equation: this.state.lastAnswer,
        restart:false,
        lastAnswer:false
      });
    }

    console.log(this.state.lastAnswer);//expected to be false
    
    //starting a new calculation
    if(this.state.restart){
      this.setState({
        display: ["0"],
        equation: [],
        restart:false
      });
    }

//switch statement...

Thanks.

Have you checked out React Hooks?
componentWillUpdate( ) function.

1 Like

Thanks, @Cowwy! I think that’s the proper way to do it though I fixed mine using a not so proper way.