0

I am fairly new to JS and jumping to the gun on React.

You see i am trying to create calculator where there are 2 input register, Register A and B, and initialize with null value. The purpose of this register is to contain a string-converted number. Why am i doing that? so everytime user click a number, the new digit would be appended in register

So I use conditional block to check whether Register A or B is empty. If both of them are null, the value is inserted into regA, if reg is filled the value is inserted into reg B, if both of them are full, RegA will copy the value of Reg B and Reg B would be empty

import {useState } from 'react'

const Calculator = () => {

const [operator , setOperator]= useState(null)
const [registerA, setRegisterA] = useState(null)
const [registerB, setRegisterB] = useState(null)

const operatorSetter = (operand)=>{
    operator = operand
    console.log(operand)
}

const registerSetter = (number)=>{
    if (!registerA==null && !registerB==null){
        setRegisterA(registerB+number)
        setRegisterB(null)
        console.log("Not")
    }

    if(registerA==null && registerB==null){
        setRegisterA(number)
        console.log("Net")

    if (!registerA==null && registerB==null){
        setRegisterB(number)
        console.log("Nit")
    } 
    
    }

    console.log(registerA, registerB)
}

return (  
    <div>
        {/* <button onClick={operatorSetter("+")}>+</button> */}
        {/* <button onClick={operatorSetter("-")}>-</button> */}

        {/* Numeric Button */}

        <button onClick={ ()=> registerSetter("1")}>1</button>
        <button onClick={ ()=> registerSetter("2")}>2</button>
    </div>
);

}

export default Calculator;

the problem is the value keep stuck into either 1 or 2 depending on which button i click first

currently i expected to append the number like "2" into "21" and "211"

KXN
  • 1
  • Side note: Is `!registerA==null` *really* the comparison you want? Or did you mean `registerA !== null` instead? – David Jun 27 '23 at 16:32
  • Additionally, the `operatorSetter()` function is *mutating state*, which is pretty much always a recipe for bugs. Use the state setter instead, like you already do with your other state values. – David Jun 27 '23 at 16:33
  • Also, `onClick={operatorSetter("+")}` *definitely* doesn't do what you think it does. This invokes the `operatorSetter` function *on render*, not on *click*. Contrast this with your other buttons. Overall, it looks like you're running into a wide variety of problems in your React implementation and could probably benefit from walking through some additional tutorials and starting with smaller examples. – David Jun 27 '23 at 16:35
  • @david I see, thanks for the reply, yeah I think I should go more in-depth looks in react docs. And yes, I just finished react tutorial from net ninjas that's why I used !register instead of registerA!== – KXN Jun 28 '23 at 05:51

0 Answers0