I am attempting to pull API Data from a Server using SWR & NextJS. The API Data Contains an Array, that array contains objects which contains another array. I am able to output the data from the parent array but not the child array.
Form my understanding there is a is an issue with data.location.statistics.map as it returns the error TypeError: Cannot read properties of undefined (reading 'map')
There is most likely a very simple solution, apologies this is all new to me
The Code Tried
"use client";
import React from 'react';
import useSWR from 'swr';
export default function Home() {
const resource = "https://api.npoint.io/1a3c1760fd86a94b1ff5"
const fetcher = (url: RequestInfo | URL) => fetch(url).then((res) => res.json());
const { data, error, isLoading } = useSWR(resource, fetcher)
if (error) return <div>failed to load</div>
if (isLoading) return <div>loading...</div>
return (
<div>
{data.location.map((locationData: { id: string; location: string; manager: string; }) => {
return (
<div>
<p>{locationData.id}</p>
<p>{locationData.location}</p>
<p>{locationData.manager}</p>
</div>
)
})}
{data.location.statistics.map((statisticsData: { type: string; rank: string; }) => {
return (
<div>
<p>{statisticsData.type}</p>
<p>{statisticsData.rank}</p>
</div>
)
})}
</div>
);
}
The
apiprovided returnslocationas an array. Therefore you may have to loop over thedata.locationbecause as an array,locationdoes not have properties. Thestatisticsis a property of the objects contained in thedata.locationarray among withid,locationandmanager.Since you are already mapping over it, you should access the statistics as below:
Hope it helps.