skip to Main Content

It’s only been a few days since I started learning next.js. As for now, I can’t figure out how to fetch data from api. In plain react, I used useState and useEffect to control and fetch data. But what about next.js 13.4?

import { ProductType } from '../Types/productTypes';
import Image from 'next/image';

async function getData() {
    const res = await fetch('https://dummyjson.com/products');
    if (!res.ok) {
        throw new Error('Failed to fetch data');
    }

    return res.json();
}

export default async function ProductPage() {
    const data: ProductType[] = await getData()

    return (
        <main>
            {data.map((product) => (
                <div key={product.id} className='border p-4'>
                    <h3 className='text-xl font-semibold'>{product.title}</h3>
                    <p className='text-gray-500'>${product.price}</p>
                    <Image src={product.thumbnail} alt={product.title} className='mt-4 mb-2 w-full h-48 object-contain' />
                    <button className='bg-blue-500 hover:bg-blue-600 text-white py-2 px-4 rounded'>More details</button>
                </div>
            ))}
        </main>
    );
}

My type is next:

export type ProductType = {
    id: number;
    title: string;
    description: string;
    price: number;
    discountPercentage: number;
    rating: number;
    stock: number;
    brand: string;
    category: string;
    thumbnail: string;
    images: string[];
};

2

Answers


  1. I’d like to help but it’s not quite clear what your problem is. Could you expand your question to explain what you’re expecting/what’s not working?

    Edit: If you check the structure of your response you’ll see that its type is like this:

    type DummyJsonResponse = {
      products: Product[]
      total: number
      skip: number
      limit: number
    }
    

    You can add this as a return type of your getData function:

    async function getData(): Response<DummyJsonResponse> { ... }
    

    And then map over data.products instead of data (which is not an array).

    Login or Signup to reply.
  2. In nextjs 13 by default every component is a server component which mean server component renders on server.

    if you need to use useState useEffect useRef etc, you should mark use client top in the component.

    You should call your function this way…

    async function getData() {
        const res = await fetch('https://dummyjson.com/products');
        if (!res.ok) {
            throw new Error('Failed to fetch data');
        }
    
        const data:ProductType = await res.json();
        return data;
    }
    
    

    Update Your Type

    You need to update your type with this …

    export type ProductType = {
        id: number;
        title: string;
        description: string;
        price: number;
        discountPercentage: number;
        rating: number;
        stock: number;
        brand: string;
        category: string;
        thumbnail: string;
        images: string[];
    }[];
    
    

    Just add square bracket in the last.

    In React Component

    export default async function ProductPage() {
    const response = await getData();
    
    return (
    <> {/* Return your code */} </>
     )
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search