Add Async/Await to React Fetch Request

I’m making a fetch request to this API and I’m successfully getting the data and printing it to the console. However I’m new to asynchronous calls in Javascript/React. How do add async/await in this code to delay the render upon successful fetch? I’m getting the classic Uncaught (in promise) TypeError: Cannot read property '0' of undefined because I believe that the DOM is trying to render the data that hasn’t been fully fetched yet.

import React, { useEffect, useState } from "react";

export default function News() {
  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [stories, setStory] = useState([]);

  useEffect(() => {
    fetch(
      "http://api.mediastack.com/v1/news"
    )
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setStory(result);
          console.log(result.data[0]);       // printing to console to test response
          console.log(result.data[0].title); // printing to console to test response
        },
        (error) => {
          setIsLoaded(true);
          setError(error);
        }
      );
  }, []);

  if (error) {
    return <div>Error: {error.message}</div>;
  } else if (!isLoaded) {
    return <div>Loading...</div>;
  } else {
    return (
      <div>
        <p>{stories.data[0].title} </p> // this is the where render error is
      </div>
    );
  }
}

40 thoughts on “Add Async/Await to React Fetch Request”

  1. Hi there I am so glad I found your blog page, I really found
    you by error, while I was browsing on Yahoo for something else, Anyhow I am here now and would just like to say many thanks for
    a fantastic post and a all round entertaining blog (I also love the theme/design), I don’t have time
    to read through it all at the minute but I have bookmarked it and also included your RSS feeds, so when I have time I will be back to read
    a lot more, Please do keep up the awesome jo. http://antiibioticsland.com/Cephalexin.htm

    Reply

Leave a Comment