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

Time:12-15

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!

CodePudding user response:

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

CodePudding user response:

Async functions always return a promise. The time when you call that function it will give you back a promise instantly. You have used await inside the function and it is waiting for getGroup promise.

In normal javascript function console.log(await) this will fix the issue but in react you have to do it inside a another function because you cant make react components async (at least not in React 17 and below)

  • Related