This project demonstrates data fetching using Client-Side Rendering (CSR) and Server-Side Rendering (SSR) in a Next.js application. It fetches and displays product and book data from external APIs, showcasing the differences in implementation between CSR and SSR.
CSR (Client-Side Rendering):
fetch
API.SSR (Server-Side Rendering):
Reusable UI components (Card
, CardContent
, CardFooter
) to display fetched data in an organized manner.
Clone the repository:
git clone https://github.com/Tahasaif3/CSR-SSR-Data-Fetching-Assignment.git
cd CSR-SSR-Data-Fetching-Assignment
Install dependencies:
npm install
# or
yarn install
Run the development server:
npm run dev
# or
yarn dev
Open http://localhost:3000 in your browser to view the application.
CSR Page (app/client-side/page.tsx
):
useEffect
hook.SSR Page (app/server-side/page.tsx
):
fetch
API with cache: 'no-store'
for fresh data.'use client';
import { useState, useEffect } from 'react';
import { Card, CardContent, CardFooter } from '@/components/ui/card';
interface Product {
id: number;
title: string;
price: number;
category: string;
image: string;
}
export default function ClientSidePage() {
const [products, setProducts] = useState<Product[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('https://fakestoreapi.com/products')
.then(res => res.json())
.then(data => {
setProducts(data);
setLoading(false);
});
}, []);
if (loading) {
return <div>Loading...</div>;
}
return (
<div>
{products.map(product => (
<Card key={product.id}>
<CardContent>{product.title}</CardContent>
</Card>
))}
</div>
);
}
import { Card, CardContent, CardFooter } from '@/components/ui/card';
interface Book {
id: number;
name: string;
type: string;
available: boolean;
}
async function getBooks(): Promise<Book[]> {
const response = await fetch('https://simple-books-api.glitch.me/books', { cache: 'no-store' });
if (!response.ok) {
throw new Error('Failed to fetch books');
}
return response.json();
}
export default async function ServerSidePage() {
const books = await getBooks();
return (
<div>
{books.map(book => (
<Card key={book.id}>
<CardContent>{book.name}</CardContent>
</Card>
))}
</div>
);
}