Home > database >  Async / await code not called in useEffect function
Async / await code not called in useEffect function

Time:07-20

I can't figure out why the await function setDoc is not completed in my example below when I launch my react native app for the first time.

When I launch it a second time however, it works well.

Can you help me?

useEffect(() => {

    registerForPushNotificationsAsync().then(async token => {
      
      // The following gets called
      console.log("Before await")

      // The following does not complete when I first launch the app.
      await setDoc(doc(db, "devices", token), { test: "test" })
        .then(x => {
          // The following does not get called
          console.log('Sucess')
          
        })
        .catch(error => {
          // The following does not get called
          console.log('Error')
        })

      // The following does not get called
      console.log("After await")
    });

    return () => {};
  }, []);

with registerForPushNotificationsAsync defined outside useEffect as:

async function registerForPushNotificationsAsync() {
  ...
  return token;
}

Thank you.

CodePudding user response:

Try moving the async function outside of the useEffect function:

const someAsyncFunc = async () => {
    console.log("Before await")
    try {
        const token = await registerForPushNotificationsAsync();
        await setDoc(doc(db, "devices", token), { test: "test" })
        console.log('Success')
    } catch (error) {
        /// do error handling
        console.log(error);
    }
    console.log("After await")
}

useEffect(() => {
  someAsyncFunc();
}, []);

CodePudding user response:

use async await as follows.

useEffect(() => {
  registerForPushNotificationsAsync().then(async (token) => {
    // The following gets called
    console.log('Before await');

    try {
      await setDoc(doc(db, 'devices', token), { test: 'test' });
      console.log('Sucess');
    } catch (error) {
      console.log('Error');
    }

    // The following does not get called
    console.log('After await');
  });

  return () => {};
}, []);

CodePudding user response:

If there a reason why you want to use await there ?

Otherwise you should try to do this using only .then and syncronious code :

useEffect(() => {

    return registerForPushNotificationsAsync().then(async token => {
    
    // The following gets called
    console.log("Before await")

    // The following does not complete when I first launch the app.
    return setDoc(doc(db, "devices", token), { test: "test" })
        .then(x => {
        // The following does not get called
        console.log('Sucess')
        
        })
        .then(() => {
            // The following does not get called
            console.log("After await")
            return () => {};
        })
        .catch(error => {
        // The following does not get called
        console.log('Error')
        })
    });
}, []);
  • Related