const [businessHour, setBusinessHour] = useState("");
const getHour = () => {
console.log(businessHour);
}
setBusinessHour('1234');
getHour();
The result show "" instead of "1234", any way to update the variable ? Thank you
const [businessHour, setBusinessHour] = useState("");
const getHour = () => {
console.log(businessHour);
}
setBusinessHour('1234');
getHour();
The result show "" instead of "1234", any way to update the variable ? Thank you
4
Answers
please update your entire code of a component. The result will show empty string
""
first, and then when state is changed, it will print"1234"
. so there will be multiple logging instead of just one.I faced the same problem earlier. My workaround is to create a temporary variable to use because the state has not updated yet.
A better way to do is , use the useEffect callback :
so here basically
useEffect
will be called whenevergetHour
changes which is dependent onbusinessHour
Hope it helps.
You can update state if you want to update some views followed by that state.
In the case above, you don’t need to update state.
Then you will get the result you want.