DEV Community

Anunoy Dussa
Anunoy Dussa

Posted on

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! 
    }, []);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)