Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
Next.js Manejador mecanografiado del objeto JSON

Estoy trabajando en un proyecto personal con Next.js y Typescript. Tengo una llamada a la API en hello.ts que viene de forma predeterminada con la aplicación. Agregué un archivo JSON allí. Actualmente, tengo problemas para mapear ese JSON y representar su contenido. Por el momento, el JSON está dentro del useState, pero cuando intento hacer algo con él, el navegador y la consola me dan errores.

Este es hello.ts con un JSON de msaller ubicado aquí /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" } ] }) }

Aquí es donde llamo a los components/container ubicados en la API:

 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;

Además, ¿cómo puedo representar los datos solo si tiene valores dentro?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Establezca el valor predeterminado de apiDetails en nulo y agregue una verificación para ver si se han cargado los datos.
Además, debe map en apiDetails.frames :

 import { useEffect, useState } from 'react'; import { FrameContainerProps } from '../../types'; const FrameContainer: React.FC<FrameContainerProps> = () => { const [apiDetails, setapiDetails] = useState<any>(null); useEffect(() => { fetch('http://localhost:3000/api/hello') .then((res) => { return res.json(); }) .then((data) => { setapiDetails(data); }) .catch((err) => { return console.error(err); }); }, []); if (!apiDetails) return <>Loading data...</>; return ( <> {apiDetails.frames && apiDetails.frames.map((frame) => ( <h3> {frame.description || ''} </h3> ))} </> ); }; export default FrameContainer;
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!