Search code examples
reactjsasynchronousasync-awaitfetch

React & Fetch async/await... Why I'm receiving a promise?


I'm having some troubles about react, fetch and async/await.

I have this code as a fetch wrapper:

export const fetcher = (url, options = null) => {

  const handle401Response = error => {
    throw error;
  }

  const isResponseValid = response => {
    if (!response.ok)
      throw response;
    else
      return response.json();
  }

  return fetch(url, { ...options, credentials: 'include' })
    .then(isResponseValid)
    .catch(handle401Response);
}

Then I define some API calls functions like:

export const getGroups = (id = null) => {
  return fetcher(`${API_GROUP_URL}${id !== null ? `?id=${id}` : ''}`);
}

And then I try to use it like:

export function SomeComponent(props) {

  const groups = async () => {
    try {
      const ret = await getGroups();
      return ret;
    } catch (err) {
      console.log(err);
    }
  };

  console.log(groups());
  
  return <h1>Component</h1>
}

The result in console is: Promise{}. I have read docs about async/await but can't understand why await is not waiting for promise to end.

Thanks in advance!


Solution

  • export function SomeComponent(props) {
    
      const [data, setData] = useState()
    
      const groups = async () => {
       
      };
    
      useEffect(() => {
    
        const fetchData = async () => {
        try {
          const ret = await getGroups();
          // process and set data accordingly
          setData(ret)
        } catch (err) {
          console.log(err);
        }
        }
    
        // fetch data inside useEffect
        fetchData()
    
      }, [])
    
     // console.log(groups());
      
      return <h1>Component {data?.prop}</h1>
    }
    

    Hope this gives you an idea on how to fetch in a functional component