Calculator Help. Reset state after equals pressed?

Hi guys,

I have been working on my calculator app for a few weeks now having redone it several times. It is by far the hardest project I have done so far but feel I am really close now.

Although I might add some more features, the one problem I am really struggling with that hopefully resolves the last piece of logic is I after a user presses ‘=’ I want the currentNumber and input to reset although still stay on screen (so user can see sum and answer) until user presses a number button.

My logic seems sound to me and I don’t understand why it doesn’t work but am obviously doing something wrong or don’t fully understand how state is working.

So when user presses ‘=’ it currently should set equalPressed state to true.
After user then presses a number it adjusts state and resets equalPressed to false.

const [equalPressed, setEqualPressed] = useState(false);
    // calculate current sum in the input state
    const calculateSum = () => {
        setEqualPressed(true);
        let newInput = undefined;
        
        // remove operator if input ends in one
        if (input.endsWith('</span> ')) {
            newInput = input.substring(0, input.length - 35);
            setInput(newInput);
        }
        setCurrentNumber(safeEval(newInput));
    }
    // add new numbers to state
    const appendNumber = num => {
        if (equalPressed) {
            setCurrentNumber(Number(num).toString());
            setInput(num);
            setEqualPressed(false);
        } else {
            setCurrentNumber(Number(`${currentNumber}${num}`).toString());
            setInput(`${input}${num}`); 
        }
    }

Here is the full code. Appreciate any help. Full disclosure: The design is based off a design I found on dribbble and wanted to try and recreate.

After a quick glance, I’d say that it’s because your setInput callback is changing value in App.js which result in rerendering the button, effectively resetting its state.
Try to move equalPressed into App.js.

1 Like

Thank you so much it works perfectly now. This is likely the reason this project took me sooo long. I had alot of other state in the Button.js component but as they ended up getting shared with other components they naturally moved to App.js and then things that didn’t work before started to work :see_no_evil:

Thanks again!