Home > Mobile >  Display loading spinner during call when using fetch API
Display loading spinner during call when using fetch API

Time:05-09

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)
        })


}, [])

CodePudding user response:

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

CodePudding user response:

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>

  • Related