I’m new to React and am using the Fetch API to retrieve data from an external JSON file.
I’ve noticed something about how it works that I don’t fully understand. In each tutorial I’ve read it seems you need to wrap the output in a conditional like {data.length > 0 && ( // Do something )}
for it to work.
EG with my code:
const [data,setData]=useState([]);
const getData=()=>{
fetch('https://www.someplace.com/jsonfile'
,{
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}
)
.then(function(response){
return response.json();
})
.then(function(myJson) {
setData(myJson);
});
}
useEffect(()=>{
getData()
},[])
return (
<div className="App">
<header className="App-header">
{data.length > 0 && ( // If I remove this is breaks
<Welcome text={"This data is from a JSON feed: " + data[1].title}/>
)}
</header>
</div>
);
If I change
{data.length > 0 && (
<Welcome text={"This data is from a JSON feed: " + data[1].title}/>
)}
To just
<Welcome text={"This data is from a JSON feed: " + data[1].title}/>
The App still compiles, but I get the error
Uncaught TypeError: Cannot read properties of undefined (reading 'title')
In my browser’s console.
Now, I’d expect that error if the code failed to fetch the JSON file but if I put the length check conditional back it works no matter what.
Why does it seem that adding that conditional makes the Fetch work? Is this because the Fetch API is called multiple times and always fails the first time?
2
Answers
You need to delay rendering the template referencing
data[1].title
until data has been fetched. Becausedata
is an empty array until that point, which meansdata[1]
isundefined
.You get the following error when trying to read any property of
undefined
:Note: technically, your check is not proper. If the response comes back with an array of only 1 item (or any other response which has an
undefined
ornull
[1]
), you’ll still get the error. A better check would be:You are initial values data = [] and React will load the Welcome component once the view is painted and trying to access data1.title which is unavailable at the initial state. that’s the reason for the error. Try
in your Welcome component. Remember data fetch is async task and will not be ready on Load ie when useEffect() calls. Conditional rendering