Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve a promise after react hooks setState complete?

I need to resolve the promise after setState complete but in react hooks setState (useState) does not have a callback function.

React hooks version of this code:

handleBeforeGetContent = () => {
    return new Promise((resolve, reject) => {
        this.setState({ key: 'updatedValue' }, () => resolve());
    });
}
like image 540
Chanandrei Avatar asked Dec 17 '22 15:12

Chanandrei


1 Answers

You can use async function inside the useEffect like below.

  const [isLoadingComplete, setLoadingComplete] = React.useState(false);


  React.useEffect(() => {
        async function loadDataAsync() {
          try {    
            await loadAsyncSomething();
          } catch (e) {
            console.warn(e);
          } finally {
            setLoadingComplete(true);
          }
        }

        loadDataAsync();
      }, []);
like image 155
Bariscode Avatar answered Dec 26 '22 12:12

Bariscode