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>
);
}
}