Currently, I am working on a personal project using Next.js and Typescript. Within the hello.ts file that is included with the app by default, I have added a JSON file. However, I am facing difficulties in mapping the JSON data and rendering its content. The JSON data is currently stored within a useState hook, but when attempting to manipulate it, both the browser and console display errors.
Below is the example of the hello.ts file containing a smaller JSON dataset located at /pages/api/hello:
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from 'next'
type Data = {
clientName: string
campaignName: string
userName: string
frames: {
id: string
asset: string
subheading: string
description: string
link: string
}[]
}
export default function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
res.status(200).json({
userName: "username",
frames: [
{
id: "1",
asset: "",
subheading: "Instagram",
description: "",
link: "someurl.com"
},
{
id: "3",
asset: "",
subheading: "Facebook",
description: "username Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean sollicitudin metus vitae",
link: "someurl.com"
}
] })
}
This is where the API call is made, located in components/container:
import { useEffect, useState } from "react";
import { FrameContainerProps } from "../../types";
const FrameContainer: React.FC<FrameContainerProps> = () => {
const [apiDetails, setapiDetails] = useState<any>();
useEffect(() => {
fetch('http://localhost:3000/api/hello')
.then((res) => {
return res.json();
})
.then(
(data) => {
setapiDetails(data);
},
(err) => {
return console.error(err);
}
);
}, []);
return (
<>
{Object.entries(apiDetails).map(detail => (
<h3>{detail.frames[i].description ? detail.frames[i].description : ''}</h3>
))}
</>
)
}
export default FrameContainer;
Additionally, I am seeking guidance on how to only render the data if it contains values.