Home > other >  ReactJS compontent state not update correctly
ReactJS compontent state not update correctly

Time:10-15

Consider I got a component called Test

import {useEffect, useState} from "react";

const Test = (props) => {
    const [Amount, setAmount] = useState(1);

    useEffect(()=>{
        if(props.defaultAmount){
            setAmount(props.defaultAmount)
        }
        props.getResult(Amount);
    },[props, Amount])
    return (
        <>
            <span>Amount is: {Amount}</span>
            <input value={Amount} onChange={(e)=>setAmount(e.target.value)}/>
        </>
    )
}

export default Test;

I use this in two different components (actually my pages), one with defaultAmount another without.

Page 1:

<Test getResult={getAmountResult} defaultAmount={25}/>

But this not update result and it back to default one!

Page 2:

<Test getResult={getAmountResult} />

it works fine!

Working Demo

Is there any solution to avoid this?

CodePudding user response:

try to change your code like this

import {useEffect, useState} from "react";

const Test = (props) => {
    const [Amount, setAmount] = useState(1);


    useEffect(() => {
        props.getResult(Amount);
    }, [Amount])

    useEffect(()=>{
        if(props.defaultAmount){
            setAmount(props.defaultAmount)
        }
    },[props.defaultAmount])
    return (
        <>
            <span>Amount is: {Amount}</span>
            <input value={Amount} onChange={(e)=>setAmount(e.target.value)}/>
        </>
    )
}

export default Test;

in your current implementation you always overwrite the amount state with the default

CodePudding user response:

Your useEffect function is the culprit. You're setting the Amount back to defaultAmount everytime Amount changes, thus overriding the user input.

Try updating the condition within useEffect before you set the value, to make sure you don't override the user input, something like:

useEffect(()=>{
    if(props.defaultAmount && Amount === 1){ // Checking if the amount is still the initial value
        setAmount(props.defaultAmount)
    }
    props.getResult(Amount);
},[props, Amount])

CodePudding user response:

When input changes, setAmount called, it will update amount and trigger useEffect hook which will set amount to default value. Try this

import { useEffect, useState } from "react";

const Test = (props) => {
  const [amount, setAmount] = useState(props.defaultAmount);

  useEffect(() => {
    if (amount) {
      props.getResult(amount);
    }
  }, [amount, props]);

  return (
    <>
      <span>Amount is: {amount}</span>
      <input value={amount} onChange={(e) => setAmount(e.target.value)} />
    </>
  );
};

export default Test;
  • Related