Help With The React Calculator

Hey everyone! I have been building my react calculator and I think it is almost finished but there are two things I couldn’t handle.
live app
source code

First in order to make the operation I use setNumber((prev) => eval(prev).toString()); but if user does something like 5/* then app crashes. So if user does something like that I wanted to setNumber state to “Syntax Error” I am not sure if it is the right approach but anyways I tried

 const calculate = () => {
    try {
      setNumber((prev) => eval(prev).toString());
    } catch (error) {
      setNumber(() => "Syntax Error");
    }
  };

But I couldn’t make it work. What am I missing?

Second problem is that when user presses CE to delete 1 number it works. onClick={() => setNumber((prev) => prev.slice(0, -1))
I’ve tried the same with handleKeyPress

    if (e.keyCode === 8) {
      setNumber((prev) => prev.slice(0, -1));
    }

But it seems when I press backspace it deletes 2 number instead of 1. Why is that?

And as always thank you for the help.

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