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

186
Visualizações
Call async function while opening modal in React

I have a functional component and in it I have a function that fetches the cart items of the current user and I want to call it when I am opening a modal (which will show a preview of the current cart items). This doesnt happen in the first moment when I open the modal, but only if I click again on the modal somewhere.

This is the code:


    const handleOpen = () => {
    
        fetchUserCart();
        console.log(currentUserCart);
        setOpen(true);
      
    };
    
    const fetchUserCart = async () => {

        const q = query(collection(db, "users"), where("uid", "==", user?.uid));
        const doc = await getDocs(q);
        const data = doc.docs[0].data();  
        setCurrentUserCart(data.cart);
        console.log(currentUserCart);

    }

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You need to wait the end of fetchUserCart in handleOpen to log the result. At the first iteration it doesn't wait until your fetch function is finished to go to the next step console.log(currentUserCart);

Do something like this :

    const handleOpen = () => {
        fetchUserCart()
        .then(userCart => console.log(userCart))
      };
    
      const fetchUserCart = async() =>{
        const q = query(collection(db, "users"), where("uid", "==", user?.uid));
          const doc = await getDocs(q);
          const data = doc.docs[0].data();  
          setCurrentUserCart(data.cart);
          return (data.cart)
     }
about 4 years ago · Santiago Trujillo 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