简体   繁体   中英

Loading spinner while fetching an api in react app not showing

When the website loads for the first time the fetched data from an api don't show.But after one reload the products are shown . Tried to use a loading spinner while loading the data. The spinner won't show either. How can I show the the loaded data on the first time and while loading the products the Loading spinner will be shown.

const [isLoading, setIsLoading] = useState(false);


 useEffect(() => {
setIsLoading(true);

fetch(" https://hidden-citadel-3557.herokuapp.com/inventory")
  .then((res) => res.json())
  .then((data) => setInventories(data));
setIsLoading(false );  }, []); `
  if (isLoading) {
return <Loading></Loading>  }

Move "setIsLoading(false)" to the second ".then", like this:

const [isLoading, setIsLoading] = useState(false);


 useEffect(() => {
   setIsLoading(true);

fetch(" https://hidden-citadel-3557.herokuapp.com/inventory")
  .then((res) => res.json())
  .then((data) => {
     setIsLoading(false);
     setInventories(data)
   });
 }, []); 

  if (isLoading) {
return <Loading></Loading>  }

Based on your code, your approach is not a very viable one.

Here's what I would do.

  1. Use a separate function for loading the data.
function loadData()
{
   setLoading(true);
   fetch(" https://hidden-citadel-3557.herokuapp.com/inventory")
     .then((res) => res.json())
     .then((data) => {
        setInventories(data);
        setLoading(false);
     });
}
  1. Then perform your effect:
 useEffect(loadData,[]);
  1. In your jsx, use the loading variable to render <loading> element based on loading state varibale value:

{ loading ? <loading></loading> : ""}

This works for me:

import React, { useState, useEffect } from "react";

const Index = () => {
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch(
        "https://627a5a9773bad50685876437.mockapi.io/users"
      );
      await response.json();
      setIsLoading(false);
    };
    fetchData();
  }, []);

  return isLoading ? <p>Loading</p> : <p>Loaded!</p>;
};

export default Index;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM