Hi all,
Beginner with React. Trying to display API data but the app loads and tries to display the API data before it has loaded, resulting in “Cannot read properties of undefined” error. To remedy this I am attempting to build a loading component so that the app isn’t trying to display data it doesn’t yet have. Also posted this to r/LearnReact
Here is my code currently:
import { useEffect, useState } from “react”;
import Marquee from “react-fast-marquee”;
const News = () => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
setLoading(true);
(async function getNewsFromApi(){
const response = await fetch(
“API_KEY_HERE”
);
const responseJson = await response.json();
console.log(“json”, responseJson);
setData(responseJson);
})();
setLoading(false);
}, []);
if (loading) {
return <h1> Data is loading…</h1>
}
return (
<div > <Marquee gradientColor=”” speed=”120″> {data.length > 0 && data.articles.map((item)=> <h1>{item.title} </h1>)} </Marquee> </div> ) } export default News
Any advice or support is greatly appreciated.
submitted by /u/shinysilvereye
[link] [comments]