0
0
NextJSframework~30 mins

Repository pattern for data access in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Repository Pattern for Data Access in Next.js
📖 Scenario: You are building a simple Next.js app that fetches user data. To keep your code clean and organized, you will use the repository pattern. This means you will create a separate module to handle data fetching, so your components stay simple and focused on showing the data.
🎯 Goal: Build a repository module that fetches user data from a mock API and use it in a Next.js page component.
📋 What You'll Learn
Create a repository module with a function to fetch user data
Add a configuration variable for the API endpoint URL
Implement the data fetching logic inside the repository function
Use the repository function inside a Next.js page component to display user names
💡 Why This Matters
🌍 Real World
The repository pattern helps keep your data fetching code organized and reusable, making your Next.js apps easier to maintain and test.
💼 Career
Many companies use the repository pattern to separate concerns in their codebase. Knowing this pattern is useful for frontend and full-stack developer roles.
Progress0 / 4 steps
1
Create the initial user data array
Create a constant called mockUsers that is an array of objects. Each object should have id and name properties with these exact values: { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, and { id: 3, name: 'Charlie' }.
NextJS
Need a hint?

Use const mockUsers = [ ... ] to create the array with the exact user objects.

2
Add API endpoint configuration
Create a constant called API_URL and set it to the string 'https://example.com/api/users'.
NextJS
Need a hint?

Use const API_URL = 'https://example.com/api/users' to store the API endpoint.

3
Implement the repository fetch function
Create an async function called fetchUsers that returns the mockUsers array. Use return mockUsers; inside the function body.
NextJS
Need a hint?

Define async function fetchUsers() and inside it return mockUsers;.

4
Use the repository in a Next.js page component
Create a default exported async function component called UsersPage. Inside it, call fetchUsers() and store the result in a constant called users. Return a JSX <main> element containing an unordered list <ul>. Map over users to create list items <li> showing each user's name. Use user.id as the key for each list item.
NextJS
Need a hint?

Define export default async function UsersPage(), call await fetchUsers(), and return JSX with a list of user names.