'How to fix loading spinner when using useEffect Hooks with dependency list?

I am facing one problem when trying to add a spinner. My problem is when I add "product" dependency in useEffect hooks then my loading spinner always spinning and data not showing. Here is my code :

const [product, setProduct] = useState([]);
   const [msg, setMsg] = useState('');
   const [loading, setLoading] = useState(false);
   const navigate = useNavigate();

   // show all products on the manage inventory page

   useEffect(() => {
      setLoading(true);
      (async () => {
         const data = await fetchAllProduct();
         if (data) {
            setProduct(data);
            setLoading(false);
         }
      })();
   }, [product]);

Bellow the return code >>

{
               loading === false ? <ProductTable
                  viewProductHandle={viewProductHandle}
                  deleteProductHandle={deleteProductHandle}
                  product={product}>
               </ProductTable> : <Spinner></Spinner>
            }

So how do I fix that? pls, help me...



Solution 1:[1]

It's happening because you're only setting your loading state to false when data is a truthy. Moreover, your loading state can start with a true value, and you set it to false inside your useEffect after finishing the request. This way you're going to avoid initializing the state with a false value, setting it to true, and then back to false.

I also think your product state doesn't need to be on dependency array, because you're only setting it once, after the fetchAllProduct() call, so it'll probably not change again, as you're not passing setProducts down to your ProductTable component.

So your code should be something like this:

   const [product, setProduct] = useState([]);
   const [msg, setMsg] = useState('');
   const [loading, setLoading] = useState(true);
   const navigate = useNavigate();

   // show all products on the manage inventory page

   useEffect(() => {
      (async () => {
         const data = await fetchAllProduct();
         if (data) {
            setProduct(data);  
         }
         setLoading(false);
      })();
   }, []);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1