skip to Main Content

I’ve got a Django RESTapi and the output data is like this:

{
"count": 1000,
"next": "http://127.0.0.1:8000/store/products/?page=2",
"previous": null,
"results": [
    {
        "id": 648,
        "title": "7up Diet, 355 Ml",
        "slug": "-",
        "description": "tincidunt eget tempus vel pede morbi porttitor lorem id ligula suspendisse ornare consequat lectus in est",
        "inventory": 82,
        "unit_price": 79.07,
        "price_with_tax": 86.977,
        "collection": 5,
        "images": [
            {
                "id": 1,
                "image": "http://127.0.0.1:8000/media/store/images/joan-tran-reEySFadyJQ-unsplash.jpg"
            },
            {
                "id": 4,
                "image": "http://127.0.0.1:8000/media/store/images/grant-ritchie-n_wXNttWVGs-unsplash_uJitfkC.jpg"
            }
        ]
    },  ...

I wanna connect this to my nextjs(13) app.
I can access all the properties through the following code :

export default async function ProductsAll() {

const response = await fetch('http://127.0.0.1:8000/store/products/');
const { results } = await response.json();

return (
    <>
        <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3 p-4">
            {results?.map((item: any) => (
                <div key={item.id} className="card card-compact bg-base-100 h-80 shadow-xl">
                    <figure><Image height={500} width={500} src={item.image} alt={item.title} /></figure>
                    <div className="card-body">
                        <h2 className="card-title truncate hover:text-clip">{item.title}</h2>
                        <p className="truncate hover:text-clip">{item.description}</p>
                        <div className="card-actions justify-end">
                            <button className="btn btn-outline btn-accent md:btn-md">
                                <Link href={item.slug}>Buy Now</Link>
                            </button>
                        </div>
                    </div>
                </div>
            ))}
        </div>
    </>
)

}

but the images return an object with multiple values in it.

How can I use the first image from the images object inside my return function?

NB: I’m using nextjs 13 with the appDir it wants me to use directly the fetch() inside the function. I’ve tried getStaticProps or other methods but it doesn’t allow that.

2

Answers


  1. Chosen as BEST ANSWER

    <Image height={500} width={500} src={item?.images[0]?.image || '/images/placeholder-image.webp'} alt={item.title} />

    so I had to add or logic. Coz, if the response returns an empty array, in that case should provide a default image.


  2. use item.images[0].image to get the initial image value.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search