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

101
Vistas
I'm fetching data from an API in an async function in React and it works fine, but when I return the data I get a pending promise

I have the following React and TypeScript code:

const fetchData = async () => {
    const res: any = await fetch("https://api.spotify.com/v1/search?q=thoughtsofadyingatheist&type=track&limit=30", {
      method: "GET",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        Authorization: "Bearer BQD2JKxAuqmgsNKgWx6JiRMCskc3l1FK3VsHfOah3ey86GC8EmGBlrEGAfTCyVB1cFo2TDVQYQm8RvB_YQD6V9cXUf_HER0dfBeLc_AZ0N56VNOrsLyt2yzK6gaD5WarThefqmZj68ODXUVrLwQYfuocahIUhWOEO4WuziwVvloE",
      },
    });
    const data: any = await res.json();
    console.log(data.tracks.items);
    return data.tracks.items;
  };
  
  useEffect(() => {
    const data: any = fetchData(); 
    console.log(data);
    setLoading(false);
  }, []);

When I print the data to the console from the fetchData function I get the expected data, but when I print it from the useEffect hook I get a pending promise like this: Promise {<Pending>}.

I'd appreciate any help.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The useEffect hook should be like the following code snippet. This happens because an async function returns always a Promise and you should await it or use asyncFunction.then(result => {}) to get its result.

  useEffect(() => {
    fetchData().then(data => { 
      console.log(data);
      setLoading(false);
    }
  }, []);

To use await in useEffect it needs to be with a IIFE unfortunately because useEffect doesn't support async functions yet.

 useEffect(() => {
   (() => async {
     const data = await fetchData();
     console.log(data);
     setLoading(false);
   })();
 }, []);
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