Home > database >  How to display a spinner when data is loading from server by fetch api in REACT JS?
How to display a spinner when data is loading from server by fetch api in REACT JS?

Time:05-08

I am developing a React app where I have to load data from the server on the home page. It takes a small amount of time when loading data from the server. I want to display a spinner when the fetch api is called. I already created a spinner component, but I don't know how to display that spinner when the fetch api is triggered.

const [product,setProduct]=useState({});
useEffect(()=>{
    fetch(`http://localhost:5000/readSingleCarsData/${id}`)
    .then(res=>res.json())
    .then(data=> {
        setProduct(data)
        setQuantity(data.quantity)
    });
},[])

CodePudding user response:

Control your loader state with hooks and use .finally() to convert your loading state back to false.

import { useEffect, useState } from 'react';

export default function Home() {
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        setLoading(true);
        fetch('/api/hello')
            .then((res) => res.json())
            .then((data) => {
                // do something with data
            })
            .catch((err) => {
                console.log(err);
            })
            .finally(() => {
                setLoading(false);
            });
    }, []);

    if (loading) {
        return <LoadingComponent />;
    }

    return <MyRegularComponent />;
}

CodePudding user response:

const [product,setProduct]=useState({})
const [isLoading, setLoading]=useState(false);

useEffect(()=>{
    setLoading(true);
    fetch(`http://localhost:5000/readSingleCarsData/${id}`)
    .then(res=>res.json())
    .then(data=> {
        setProduct(data)
        setQuantity(data.quantity)
        setLoading(false);
    });
},[]);

return isLoading ? <Spiner /> : <Component />

Try this

  • Related