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

178
Visualizações
How to render component only when data is fetched from API?

I've had a problem with refreshing page in react app with using context api. After refreshing page in my console I see this logs:

enter image description here

my context fetch data from rest api but only the third time by what cause that my span is empty after end refreshing page :/

Here is my component with using data from context api.

Header/index.tsx

  const { currentAccount } = useContext(AppContext);
  console.log("ACCOUNT: ", currentAccount);

  return (
       <span>{currentAccount?.name}</span>
  );

This is my applicationContext

ApplicationContext.tsx

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

  const checkLogin = async () => {
    console.log("checkLogin");

    setLoggedIn(false);

    const token = localStorage.getItem("session");

    if (token) {
      const decode = jwt(token);
      const query = {
        id: decode["id"]
      };
      const response: Account = await axios.get("/auth/account", query);
      setCurrentAccount(response);
      setLoggedIn(true);
    } else {
      setCurrentAccount(null);
      setLoggedIn(false);
    }
  }

Here is also my routing from App.tsx

        <AppContextProvider>
          {publicRouting.map(({ path, component }, i) => (
            <Route key={i} path={path} component={component} />
          ))}
          <Main>
            {privateRouting.map(({ path, component }, i) => (
              <Route key={i} path={path} component={component} />
            ))}
          </Main>
        </AppContextProvider>

can someone tell me how to render component only when data is already fetched from my rest api? All of this is doing async so I need to wait until data is coming to app

thanks for any help!

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

0

Me, personally, like to take the following approach when rendering this type of thing:


const RenderOnFetch = () => {
    const [data, setData] = useState({});
    const [isLoading, setIsLoading] = useState(false);

    useEffect(async () => {
        await setIsLoading(true);
        const fetchedData = await fetchData();
        setData(fetchedData);
        await setIsLoading(false);
    }, []);

    return (
    <>
        {isLoading && <p>Data is being loaded..</p>}
        {!isLoading && <p>Data has been fetched..</p>}
    </>
    )

}

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