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

176
Visualizações
How to use a bootstrap load spinner while fetching data from an external api?

While fetching information from a url takes a long time, how can I utilize the bootstrap load spinner to hide the delay and make the website looks more interactive?

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

0

I prefer to have a single state that stores all the information about the request i.e. it's status, data & error.

Based on the status field you have render the appropriate UI (like loading spinner, error screen).

I have used the state hook in the example below, you can also use the reducer hook if you prefer.

function App(props) {
  const [{ status, data, error }, setState] = React.useState({
    status: "PENDING",
    data: null,
    error: null
  });

  React.useEffect(() => {
    let isCancelled = false;
    setState({ status: "PENDING", data: null, error: null });
    fetch("https://jsonplaceholder.typicode.com/todos/1")
      .then(res => res.json())
      .then(data => {
        if (isCancelled) {
          return;
        }
        setState({ status: "RESOLVED", data, error: null });
      })
      .catch((error) => setState({ status: "REJECTED", error, data: null }));

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

  if (status === "PENDING") {
    return <p>Loading...</p>;
  } else if (status === "REJECTED") {
    return <pre>{JSON.stringify(error)}</pre>;
  } else {
    return <pre>{JSON.stringify(data)}</pre>;
  }
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div id="root"></div>

about 4 years ago · Juan Pablo Isaza Relatório

0

const [loading, setLoading] = useState(false)
useEffect(() => {
setLoading(true)
// Do your Fetch and stuff
setLoading(false)

}, [])

There ya go

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