简体   繁体   中英

the usestate hook is not working in react

Hello Guys This is how my code looks like

export default function Billing() {
    const classes = useStyles();
    const [balance, setBalance] = useState('0.00');
    const [upcoming, setUpcoming] = useState('0.00');
    const [lastmonth, setLastmonth] = useState('0.00');
    const [header, setHeader] = useState('Please Enter The Amount');
    const [open, setOpen] = useState(false);
    const [amountstate, setAmountstate] = useState(false);
    
    const [amounthelper, setAmounthelper] = useState('');
    const [sairam, setSairam] = useState(0);
    const onchange = async (e) => {
        console.log(sairam) 
        setSairam({amount: e.target.value})
    }
    const [modalchild, setModalchild] = useState(<>
    <form noValidate autoComplete="off">
       <TextField
            error={amountstate}
            type="number"
            value={sairam}
            onChange={onchange}
            label='Please enter the amount'
            helperText={amounthelper}
            variant="outlined"
        />
        <br />
        <br />
        <Button variant="contained" color="primary" onClick={() => addBalance()}>Add Balance</Button>
    </form>
    </>);
    const [country, setCountry] = useState(false);
    const [currency, setCurrency] = useState('');

 const addBalance = () => {
        console.log("Clicked :)")
        console.log(sairam) // outputs the inital value not the changed value

});
    return(<>
    <div className="balance-container">
        <div className="columns-top">
            <div className="column-top">
            <h1>${upcoming}</h1>
            </div>
            <div className="column-top">
            <h1>${balance}</h1>
            <Button variant="contained" color="primary" onClick={handleOpen}>Add Balance</Button>
            </div> 
            <div className="column-top">
            <h1>${lastmonth}</h1>
            </div>

        </div>
    </div>

    <Modal
        aria-labelledby="transition-modal-title"
        aria-describedby="transition-modal-description"
        className={classes.modal}
        open={open}
        onClose={handleClose}
        closeAfterTransition
        BackdropComponent={Backdrop}
        BackdropProps={{
          timeout: 500,
        }}
      >
        <Fade in={open}>
          <div className={classes.paper}>
            <h2 id="transition-modal-title">{header}</h2>
            
            {modalchild}
          </div>
        </Fade>
      </Modal>
     </>
    )
}

if I change the state sairam by using the function setSairam() the state is not getting updated and its only logging the initial state which is 0 i have even tried the loggint the event value of my input it works correct but the state alone is not changing please help me feel free to give me any other options

setSairam() is the asynchronous method so you can't get the updated value of sairam immediately after setSairam() .

const onchange = async (e) => {
    setSairam({amount: e.target.value})
    console.log(sairam) // This will console old value of sairam
}

You should use useEffect with adding a sairam dependency to check the updated state value.

useEffect(() => {
   console.log(sairam) 
}, [sairam]);

IMPORTANT

sairam will be the value of the TextField, so you should update the sairam to the string value, not object.

setSairam(e.target.value)

You will not get the updated value in your onChange function because that function is not aware when state is changed.

Use useCallback to get the updated value of sairam . Pass sairam in the dependency array.

const onchange = useCallback(async (e) => {
        console.log(sairam) 
        setSairam({amount: e.target.value})
    },[sairam]);

or use prevState

   setSairam(prevState => {
     console.log(sairam) 
    return ({amount: e.target.value})
  });

Another option is to pass sairam to onChange function. But I am not sure how it works since your markup is stored in state

onChange={(e)=>onchange(e, sairam)}


const onchange = async (e, sairam) => {
        console.log(sairam) 
        setSairam({amount: e.target.value})
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM