Reputation: 517
I have the following:
const [quantityKm, setQuantityX] = useState({ x: 0 });
I have a range that when it changes the following function is executed
const handleKmValue = (event) => {
const { x } = event;
setQuantityX({ x: x});
};
And then, if I change a <select>
this function must be executed
const calculatePrice = () => {
console.log(quantityKm.x);
setValueMonth((parseFloat(quantityKm.x.toFixed(2)) * valueOfKm))
};
However, I always receive the value of quantityKm.x
as 0
Upvotes: 1
Views: 79
Reputation: 580
From your comments, it sounds like your code is structured as follows:
const [quantityKm, setQuantityX] = useState({ x: 0 });
const handleKmValue = ...
const calculatePrice = ...
const handleChange = event => {
handleKmValue(event);
calculatePrice();
}
<Select onChange={handleChange} />
Instead, use:
const [quantityKm, setQuantityX] = useState({ x: 0 });
useEffect(() => {
// move the calculatePrice functionality into the effect
console.log(quantityKm.x);
setValueMonth((parseFloat(quantityKm.x.toFixed(2)) * valueOfKm))
}, [quantityKm.x]) // run effect if value's changed
<Select onChange={handleKmValue} />
Upvotes: 1