Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

236
Visualizações
Using useEffect with async?

I'm using this code:

useFocusEffect(
  useCallback(async () => {
    const user = JSON.parse(await AsyncStorage.getItem("user"));

    if (user.uid) {
      const dbRef = ref(dbDatabase, "/activity/" + user.uid);

      onValue(query(dbRef, limitToLast(20)), (snapshot) => {
        console.log(snapshot.val());
      });

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

I'm getting this error:

An effect function must not return anything besides a function, which is used for clean-up. It looks like you wrote 'useFocusEffect(async () => ...)' or returned a Promise. Instead, write the async function inside your effect and call it immediately.

I tried to put everything inside an async function, but then the off() is not being called.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Define the dbRef variable outside the nested async function so your cleanup callback can reference it, and allow for the possibility it may not be set as of when the cleanup occurs.

Also, whenever using an async function in a place that doesn't handle the promise the function returns, ensure you don't allow the function to throw an error (return a rejected promise), since nothing will handle that rejected promise.

Also, since the component could be unmounted during the await, you need to be sure that the async function doesn't continue its logic when we know the cleanup won't happen (because it already happened), so you may want a flag for that (didCleanup in the below).

So something like this:

useFocusEffect(
    useCallback(() => {
        let dbRef;
        let didCleanup = false;
        (async() => {
            try {
                const user = JSON.parse(await AsyncStorage.getItem("user"));

                if (!didCleanup && user.uid) {
                    dbRef = ref(dbDatabase, "/activity/" + user.uid);

                    onValue(query(dbRef, limitToLast(20)), (snapshot) => {
                        console.log(snapshot.val());
                    });
                }
            } catch (error) {
                // ...handle/report the error...
            }
        })();
        return () => {
            didCleanup = true;
            if (dbRef) {
                off(dbRef);
            }
        };
    }, [])
);
about 4 years ago · Juan Pablo Isaza Relatório

0

useEffect(() => {
const myFunction = async () => {
your code 
}
myFunction()
}, [])
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda