Need help in calculator project

Hi, I am a new comer to React and trying to develop front end certification project ‘calculator’ in React. I got stuck at one place I want to save the previous calculations in the previous state for chained calculation, but I am not able to do so. Can anyone please help me!!
My codepen is:

I am trying to update my previous state first-time operator key is pressed but it was updating after the second press I don’t know why?

What is making you think it isn’t being updated?

When I see things like this:

          this.setState({ previous: this.state.display });
          this.setState({
            display: "0",
            operator: e.target.textContent,
            isoperator: true,
            initiate: true
          });
          console.log(this.state.previous);

First of all, you can combine those two _setState_s into one. In fact it would be better since the second is changing what the first means.

Remember that setState is asynchronous. When you run it, it won’t have affect right away. You know it will take place in the very, very soon. Things may get batched together, including repeated states, causing weird side effects. That is why we often use the functional setState in cases like this. Combining the two, we get this:

          this.setState(state => ({
            previous: this.state.display
            display: "0",
            operator: e.target.textContent,
            isoperator: true,
            initiate: true
          }));
          console.log(this.state.previous);

Now they are combined into one call, and we use the passed in state parameter, which React guarantees to be correct.

I don’t think any of that was causing your issue, but while we were there… And onto your problem… I’m assuming that the issue is that that console.log does not show the state you expect. Remember that setState is asynchronous. So JS is not going to wait for it to finish. JS is going to move onto the next line (the log) statement whether or not the React state is updated or not.

This is a common issue for developers, so much so that React lets you pass in a callback function as the second parameter to setState.

          this.setState(state => ({
            previous: this.state.display
            display: "0",
            operator: e.target.textContent,
            isoperator: true,
            initiate: true
          }), () => console.log(this.state.previous));

That callback won’t run until after the setState has completed.


If that wasn’t your issue, please clarify.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.