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

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

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 Report

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 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!