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

91
Visualizações
Display loading spinner during call when using fetch API

how to create loading statement while it's fetching

useEffect(() => {

    fetch('https://hidden-shore-3231.herokuapp.com/allCarsHomePage')
        .then(res => res.json())
        .then(data => {
            setCards(data)
        })


}, [])
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You could try creating the loading spinner right before fetching, and then hiding / removing it after the promise is resolved.

about 4 years ago · Juan Pablo Isaza Relatório

0

Add a new state that is a boolean. When the endpoint is called update that state with true, and then when the data has been sent, and parsed, set the state back to false.

Meanwhile add a separate return that shows the spinner if the loading state is true.

const { useEffect, useState } = React;

function mockAPI() {
  return new Promise(res => {
    const json = JSON.stringify({"text": "Done!"});
    setTimeout(() => res(json), 3000);
  });
}

function Example() {

  const [ text, setText ] = useState('');
  const [ isLoading, setIsLoading ] = useState(false);

  useEffect(() => {
    function getData() {
      setIsLoading(true);
      mockAPI().then(json => {
        const data = JSON.parse(json);
        setText(data.text);
        setIsLoading(false);
      });
    }
    getData();
  }, []);

  if (isLoading) return 'Spinner';

  return (
    <div>{text}</div>
  );

}

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

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