0

I'm working on an input box that takes a value for labor, sets it as state and then later does calculations based on the number. However, I'm running into an issue where the state seems to be updating with a delay to the input. I have two other inputs that are structured similarly and not having the issue. I'm not sure what is causing this.

Here is the output seen when comparing console.log(labor) with console.log(e.target.value) (found in the second code block).

Output seen when comparing console.log(labor) with ```console.log(e.target.value) (found in the second code block).

function ProductCalculator() {
    const [labor, setLabor] = useState(70);

return (
        <div>
            <ProjectSelector
                labor={labor}
                setLabor={setLabor}
    />
    );
}

function ProjectSelector({
    labor,
    setLabor,
}) {
    function LaborInput() {
        const [name, setName] = useState("");

        function handleChange(e) {
            setName(parseFloat(e.target.value));
            setLabor(parseFloat(e.target.value));
            console.log(e.target.value); //value is correct
            console.log(labor); //value is delayed 
            
        }

        return (
            <div className="col-xs-2" id="labor-input">
                Hourly Labor Rate
                <input type="number" onChange={handleChange} value={labor} />
            </div>
        );
    }
    
    return (
        <div" className="row">
            <div>{LaborInput()}</div>
        </div>
    );
}

Betsy
  • 53
  • 7
  • 1
    State updates like `setLabor` are async processes. You can't immediately log the updated value. You could use `useEffect` to detect the changes: `useEffect(() => console.log(labor), [labor]);` – Andy Mar 09 '22 at 19:18

0 Answers0