Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

161
Vistas
How can i add React loading spinner when item is fetching from database?

Here is, my code. i want to add a spinner when data is loading then after finish loading display the data.

  {/* product section  */}
  <section className="container mx-auto my-5 row">
      <h6 className="text-center">WANT TO SEE</h6>
      <h2 className="text-center mb-5">Our Services</h2>
    {
      Products.slice(0,6)?.map((product) => {
        return <Product key={product._id} product={product}></Product>;
      })
    }
  </section>

And This is the custom hook

import { useEffect, useState } from "react";

const LoadProducts = () => {
    const [Products, setProducts] = useState([]);
    useEffect(()=>{
        fetch('http://localhost:8080/products')
        .then(res=>res.json())
        .then(data=>setProducts(data))
    },[]);
    return [Products, setProducts]
}
export default LoadProducts;
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Try this:

import { useEffect, useState } from "react";

const LoadProducts = () => {
    const [Products, setProducts] = useState([]);
    const [loading, setLoading] = useState(false);
    useEffect(()=>{
        setLoading(true);
        fetch('http://localhost:8080/products')
        .then(res=>res.json())
        .then(data=>setProducts(data))
        .finally(()=>setLoading(false))
    },[]);
    return [Products, setProducts, loading]
}
export default LoadProducts;

Note the custom hook now returns [Products, setProducts, loading].

Now you can add some conditional code to your JSX that shows a loading spinner while loading is true

  {/* product section  */}
  <section className="container mx-auto my-5 row">
      <h6 className="text-center">WANT TO SEE</h6>
      <h2 className="text-center mb-5">Our Services</h2>
    {loading ? (
      <MyLoadingSpinner/>
     ) : (
      Products.slice(0,6)?.map((product) => {
        return <Product key={product._id} product={product}></Product>;
      })
    )}
  </section>
about 4 years ago · Juan Pablo Isaza Denunciar

0

I would do something like this but you can customize it to your needs. The trick is really to create a loading state which initially will be false. When you start calling your api, you will set your loading to true. Once you either get a response or fail you set it to false.

import { useEffect, useState } from "react";
export default function App() {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true);
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then((response) => response.json())
      .then((json) => {
        console.log(json);
        setPosts(json);
        setLoading(false);
      })
      .catch((err) => {
        console.log(err);
        setLoading(false);
      });
  }, []);

  if (loading) {
    return <div>I am loading</div>;
  }
  return (
    <div>
      {posts.map((post) => (
        <p>{post.title}</p>
      ))}
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda