'How to get the lastest product from API

I have a component to render only the latest product gets from 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;

The JSON from API looks like this:

{
  "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
    }
  }
}

The highest id from JSON is the latest product, I haven't figured out how to resolve this JSON for getting the latest product.const products = res.data[x] is used to get the specific product based on x, like an index. This is my temporary solution but not flexible to get the latest one!



Solution 1:[1]

The best solution is descending data by createdAt when getting data from the API. Otherwise, you can use this method.

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;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Isuru Madusanka