Home > Net >  React native variable not update inside function
React native variable not update inside function

Time:09-02

  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

CodePudding user response:

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.

CodePudding user response:

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);

CodePudding user response:

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.

  • Related