How to use Async/Await with Fetch API in React Component?

Hello,

I’m trying to fetch restaurants data in React using async and await and update my restaurants state with the returned restaurants response

In the code below (under Method 2) I created an async function and called await fetchRestaurants() which returns a response

I don’t understand why within the aync function, I’m able to access the list of restaurants data. However, when I return the data, it’s a promise

Can someone explain why this happens?

  const fetchRestaurants = () => {
    ...
    // returns {Promise<Array<{ name: string, rating: number,  location: string}>}
  }

   const [restaurants, setRestaurants] = useState([]);

    useEffect(() => {
        // Method 1 - works!
        const promise = fetchRestaurants();

        promise
             .then((data) => {
                 setRestaurants(data);
             })
             .catch((error) => {
                 console.error(error);
             });

        // Method 2 - doesn't work
        const asyncFetchRestaurants = async () => {
            try {
                const data = await asyncFetchRestaurants();
                console.log("INSIDE", data); // this prints out the list of restaurants
                return data; // why does this return a promise?
            } catch (error) {
                console.error(error);
            }
        };

        const data = asyncFetchRestaurants(); // why is data a promise and not a list of restaurants
        console.log("OUTSIDE", data); // this prints out a promise!
        setRestaurants(data) // this doesn't work! 
    }, []);

That is what async functions do.

MDN: async function

Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.

You can pass the data from the function to something else or you can return it and use the promise at the call site.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.