Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!