Home > OS >  I'm fetching data from an API in an async function in React and it works fine, but when I retur
I'm fetching data from an API in an async function in React and it works fine, but when I retur

Time:08-29

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.

CodePudding user response:

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);
   })();
 }, []);
  • Related