Home > Software design >  How can I hide Spinner Loader after all data is fetched - ReactJS
How can I hide Spinner Loader after all data is fetched - ReactJS

Time:11-11

How can I hide the loading spinner after all the data has been fetched from the API? I have a laravel api that outputs paginated data. I am using reactjs to display the data with scroll event. Now I want to hide the spinner when all the data has been fetched. Or add something like No more data

Here is my code

function Training() {
let navigate = useNavigate();
const [fruits, setFruits] = useState([]);
const [limit, setLimit] = useState(6);
const [isLoading, setIsLoading] = useState(true);
const [loading, setLoading] = useState(false);

useEffect(() => {

    let isMounted = true;

    axios.get(`/api/fruits?page=1&limit=`   limit).then(res => {
        if (isMounted) {
            if (res.data.status === 200) {
                setFruits(res.data.fruit);
                setIsLoading(false);
                setLoading(false);
                console.warn(res.data.fruit.length)
            }
        }
    });
    return () => {
        isMounted = false
    };
}, [limit]);

useEffect(() => {

    const handleScroll = (e) => {
        const scrollHeight = e.target.documentElement.scrollHeight
        const currentHeight = e.target.documentElement.scrollTop   window.innerHeight
        if (currentHeight   1 >= scrollHeight) {
            setLoading(true);
            setLimit(limit   4)
        }
    }
    window.addEventListener("scroll", handleScroll)
    return () => window.removeEventListener("scroll", handleScroll)
}, [limit])

To show the data and the loading spinner

<div className="section">

                <div className="row">
                    {isLoading && <WidgetSkeleton cards={6} />}

                    {fruits.map((fruit) => (
                        <FruitWidget fruit={fruit} key={fruit.id} />
                    ))}

                </div>
                {loading ? <><span className="spinner-border spinner-center text-primary mb-5" role="status" aria-hidden="true"></span></> : ''}

            </div>

Please help. Thank you

CodePudding user response:

You could check if res.data.fruit.length is less than your limit. Then we know that there are no more items to fetch.

CodePudding user response:

here in you code You are turning on the setLoading to true and and to hide spin loader you need to setLoading(false) which you are doing,

The problem is you are only setting setloading to false only if you receive data, you should instead.

axios
  .get(`/api/fruits?page=1&limit=`   limit)
  .then((res) => {
    if (isMounted) {
      if (res.data.status === 200) {
        setFruits(res.data.fruit);
        console.warn(res.data.fruit.length);
      }
    }
  })
  .catch((err) => console.log(err))
  .finally(() => {
    setIsLoading(false);
    setLoading(false);
  });
  • Related