3

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)
    });
},[])
1
  • use lazy load and suspense here. Commented May 8, 2022 at 7:11

2 Answers 2

5

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 />;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Should the default/initial value for loading be true instead of false?
1
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

3 Comments

Looks good, but if you get an error, your loading will always stay as true. Better to use .finally() after everything is all done and dusted.
On catch block also setLoading(false);
Both work, for sure, although potentially an unnecessary duplication? DRY and all that... 👍

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.