skip to Main Content
  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


  1. 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.

    Login or Signup to reply.
  2. 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);
    
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
  4. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search