React native variable not update inside function

Viewed 30
  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.

const [businessHour, setBusinessHour] = useState("");
 const getHour = (businessHour) => {
   console.log(businessHour);
}

let newBusinessHour = '1234'
setBusinessHour(newBusinessHour);
getHour(newBusinessHour);

A better way to do is , use the useEffect callback :

const [businessHour, setBusinessHour] = useState("");

useEffect(() => {
getHour()
},[getHour])

 const getHour = useCallback(() => {
   console.log(businessHour);
},[businessHour])

setBusinessHour('1234');

so here basically useEffect will be called whenever getHour changes which is dependent on businessHour

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.

businessHour = '1234';
getHour();

Then you will get the result you want.

Related