'useState hook not updating in order ( The first render ) in REACT NATIVE
I was working on a react native project , and I keep facing an error while using useState Hook ! the useState update is not working in order ( before calling the function ' see the code ( setDistance' ) the console log is giving me 0 in the distance but I updated it after calling the function but if i click the button for the second time it shows me the distance
const [distance, setDistance] = React.useState(0);
const calculatePrice = () => {
if (typee === "Motorcycle" && distance > 100) {
setShowOptions(true);
Alert.alert(
"Chose another vehicle type",
"Motocycle cannot more than 100km",
[{ text: "Okay" }]
);
return;
}
};
<View>
<Button
title="Calculate Price"
onPress={() => {
setDistance(
calcCrow(
depart.latitude,
depart.longitude,
destination.latitude,
destination.longitude
)
);
console.log(distance);
console.log(typee);
calculatePrice();
}}
/>
</View>
Solution 1:[1]
SetState method does not update the state variable when it's called.
You may use useEffect hook with the state dependency to watch its changes.
I recommend you to pass distance as argument or calculate it on a useEffect hook.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shura16 |
