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

203
Views
Cómo obtener el último producto de API

Tengo un componente para representar solo el último producto obtenido de la API:

 const about = ({products}) => { const data = products.attributes console.log(data) return ( <div> <h1>{data.Name}</h1> <p>{data.Description}</p> <p>{Number(data.Price).toLocaleString('it-IT', {style : 'currency', currency : 'VND'})}</p> <p>{data.Release}</p> <p>{data.Expire}</p> <p>{data.Close ? "Close" : "Open"}</p> </div> ); } export async function getStaticProps() { const data = await fetch(myAPI) const res = await data.json() const products = res.data[0] return { props: {products} } } export default about;

El JSON de la API se ve así:

 { "data": [ { "id": 1, "attributes": { "Name": "Vĩ Hoạ", "Description": "Vĩ Hoạ", "Price": "30000", "Release": "2022-05-04", "Expire": "2022-05-26", "Close": false, "createdAt": "2022-05-09T22:28:09.622Z", "updatedAt": "2022-05-10T05:50:38.430Z", "publishedAt": "2022-05-10T05:50:12.353Z" } } ], "meta": { "pagination": { "page": 1, "pageSize": 25, "pageCount": 1, "total": 1 } } }

La identificación más alta de JSON es el último producto, no he descubierto cómo resolver este JSON para obtener el último producto. const products = res.data[x] se usa para obtener el producto específico basado en x, como un índice. ¡Esta es mi solución temporal pero no flexible para obtener la última!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

La mejor solución es descender los datos por createdAt al obtener datos de la API. De lo contrario, puede utilizar este método.

 const about = ({products}) => { const data = products.attributes console.log(data) return ( <div> <h1>{data.Name}</h1> <p>{data.Description}</p> <p>{Number(data.Price).toLocaleString('it-IT', {style : 'currency', currency : 'VND'})}</p> <p>{data.Release}</p> <p>{data.Expire}</p> <p>{data.Close ? "Close" : "Open"}</p> </div> ); } export async function getStaticProps() { const data = await fetch(myAPI) const res = await data.json() const products = res.data.sort((a, b) => b.id - a.id)[0] return { props: {products} } } export default about;
about 4 years ago · Juan Pablo Isaza 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!