I am getting a single object from an API call and when I load this works but when as soon as I reload it throws error and did not render anything and error is it did not recognizes data.picture.large larger property
import './App.css';
import a from 'axios'
import { useEffect, useState } from 'react';
function App() {
const [data,setData] = useState({})
useEffect(()=>{
a.get("https://randomuser.me/api/")
.then(res=> setData(res.data.results[0]))
.catch(err=>console.log(err))
},[])
console.log(data);
return (
<div className="App">
<img src={data.picture.large}/>
<h1>{data.gender}</h1>
</div>
);
}
export default App;
Top comments (3)
Resolved
Actually the issue is with calling object nested object property that throwing error.
Initially when we reload the data is empty and we calling its object.object.property which through error. Initially it is empty because takes some time to load and at that moment rendering occurs and it failed to load this. So error can be resolved if we put this in try catch statements or can use
data.picture?.large
for proper handling this error.
I guess api response time have some issue
Actually the issue is with calling object nested object property that throwing error.
Initially when we reload the data is empty and we calling its object.object.property which through error. Initially it is empty because takes some time to load and at that moment rendering occurs and it failed to load this. So error can be resolved if we put this in try catch statements or can use
data.picture?.large
for proper handling this error.