Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

103
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!