Let’s create a new page that fetches user data using Client-Side Rendering. Create a new file named users.tsx in the pages directory and add the following code:
1// pages/users.tsx
2
3import React, { useEffect, useState } from 'react';
4
5// Type definition for User
6interface User {
7 id: number;
8 name: string;
9 email: string;
10}
11
12// UsersPage component
13export default function UsersPage() {
14 const [users, setUsers] = useState<User[]>([]);
15 const [loading, setLoading] = useState<boolean>(true);
16
17 // Function to fetch users from an API
18 const fetchUsers = async () => {
19 const response = await fetch('https://jsonplaceholder.typicode.com/users');
20 const data = await response.json();
21 setUsers(data);
22 setLoading(false);
23 };
24
25 // Fetch users when the component mounts
26 useEffect(() => {
27 fetchUsers();
28 }, []);
29
30 // Render loading state or user list
31 return (
32 <div>
33 <h1>User List</h1>
34 {loading ? (
35 <p>Loading...</p>
36 ) : (
37 <ul>
38 {users.map(user => (
39 <li key={user.id}>
40 <strong>{user.name}</strong> - {user.email}
41 </li>
42 ))}
43 </ul>
44 )}
45 </div>
46 );
47}