I'll create a Next.js application that fetches product details from the Fakestoreapi and renders them as a list. We'll use Server Components for data fetching and create a simple UI to display the products.
Let's create the application:
Now, let me explain the code and how it works:
app/page.tsx
, we create the main page component that renders the title and the ProductList
component 1.The components/product-list.tsx
file contains the main logic for fetching and displaying the products 12:
getProducts
function that fetches data from the Fakestoreapi.ProductList
component is an async Server Component that awaits the getProducts
function and renders the list of products.Image
component from Next.js for optimized image loading and display 1.app/loading.tsx
file defines a loading spinner that will be shown while the data is being fetched 23. This is automatically used by Next.js when the page is loading.app/error.tsx
file defines an error boundary component that will be displayed if there's an error during data fetching or rendering 23. It includes a "Try again" button to reset the error state.types/product.ts
file contains the TypeScript interface for the Product type, ensuring type safety throughout the application.This application demonstrates several key features of Next.js 13 with the App Router:
loading.tsx
file 23.error.tsx
file 23.Image
component 1.To run this application, you would typically follow these steps:
create-next-app
.app
folder with the provided files.components
and types
folders and add the respective files.npm run dev
or yarn dev
.The application will fetch product data from the Fakestoreapi and display it as a responsive grid of product cards. It includes loading and error states for a better user experience.