Home > Software engineering >  How to use a bootstrap load spinner while fetching data from an external api?
How to use a bootstrap load spinner while fetching data from an external api?

Time:05-10

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?

CodePudding user response:

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>

CodePudding user response:

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

}, [])

There ya go

  • Related