Getting an error while fetching data from an API the actual data I need is in response. But when I try to access it just shows up as undefined. I added a loading function but that does not seem to fix it.
Ex Json (The original is too big)
{
"request": {
},
"response": [
{
Data I want here
}
choose.js
const [data, setData] = useState();
const [loading, setLoading] = useState(false);
useEffect(() => {
setLoading(true);
fetch(
//example API key
"https://airlabs.co/api/v9/flights?api_key=2a6ae284-575d-41d8-948a-b789734174dd&arr_icao=VOBL"
)
.then((res) => res.json())
.then((data) => {
setData(data);
})
.catch((err) => {
console.log(err);
})
.finally(() => {
setLoading(false);
});
}, []);
if (loading) {
return <div>Loading...</div>;
}
{data.response.map((post) => {
})
Full code link - https://codesandbox.io/s/heuristic-wood-meecre?file=/choose.js:2042-2072
CodePudding user response:
You need to start with the loading state being true
, because at the initial render you don't yet have data
.
Also move the rendering that you do inside the map
into its own component, otherwise you get a runtime error about too many hooks:
{data.response.map((post) => (
<Inner post={post} />
))}
(Here the component that renders each flight data is simply named "Inner")
You can see this sandbox for full demo.