Mocking data fetching helps you test and build your app without needing a real server. It lets you pretend to get data so you can see how your app works.
Mocking data fetching in NextJS
Introduction
Syntax
NextJS
async function fetchData() { // Simulate a delay await new Promise(resolve => setTimeout(resolve, 1000)); // Return mock data return { id: 1, name: 'Mock User' }; }
Use
setTimeout inside a Promise to simulate network delay.Return simple objects or arrays that look like real data from your API.
Examples
NextJS
async function fetchUser() { return { id: 1, name: 'Alice' }; }
NextJS
async function fetchPosts() { await new Promise(r => setTimeout(r, 500)); return [{ id: 1, title: 'Hello' }, { id: 2, title: 'World' }]; }
NextJS
async function fetchWithError() { await new Promise(r => setTimeout(r, 300)); throw new Error('Failed to fetch'); }
Sample Program
This React component uses a mocked fetch function to simulate loading user data. It shows a loading message, then displays the user info once loaded. If an error happens, it shows an error message.
NextJS
import { useState, useEffect } from 'react'; async function mockFetchUser() { await new Promise(resolve => setTimeout(resolve, 1000)); return { id: 1, name: 'Mock User' }; } export default function UserProfile() { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { mockFetchUser() .then(data => { setUser(data); setLoading(false); }) .catch(() => { setError('Could not load user'); setLoading(false); }); }, []); if (loading) return <p>Loading user...</p>; if (error) return <p role="alert">{error}</p>; return ( <section aria-label="User Profile"> <h1>User Profile</h1> <p><strong>ID:</strong> {user.id}</p> <p><strong>Name:</strong> {user.name}</p> </section> ); }
Important Notes
Mocking helps you build UI before backend is ready.
Always simulate delays to see loading states realistically.
Use error mocks to test how your app handles failures.
Summary
Mocking data fetching lets you pretend to get data for testing and development.
Use simple async functions with delays and fake data.
Helps you build and test UI without a real server.
Practice
1. What is the main purpose of mocking data fetching in a Next.js app?
easy
Solution
Step 1: Understand mocking concept
Mocking means pretending to get data, so you don't rely on a real server.Step 2: Identify purpose in Next.js
This helps build and test UI without waiting for real backend responses.Final Answer:
To simulate data retrieval without needing a real server -> Option DQuick Check:
Mocking = Simulate data fetching [OK]
Hint: Mocking means faking data to test without a real server [OK]
Common Mistakes:
- Thinking mocking speeds up production
- Confusing mocking with data storage
- Assuming mocking encrypts data
2. Which of the following is the correct way to create a mock async data fetch function in Next.js?
easy
Solution
Step 1: Check async function syntax
async function fetchData() { return new Promise(resolve => setTimeout(() => resolve({ data: [] }), 1000)); } correctly returns a Promise that resolves after 1 second with data.Step 2: Identify incorrect patterns
const fetchData = () => { return { data: [] }; } is synchronous, C does not return a Promise, D returns timeout ID, not data.Final Answer:
async function fetchData() { return new Promise(resolve => setTimeout(() => resolve({ data: [] }), 1000)); } -> Option AQuick Check:
Async + Promise + delay = async function fetchData() { return new Promise(resolve => setTimeout(() => resolve({ data: [] }), 1000)); } [OK]
Hint: Async functions must return a Promise to mock delays [OK]
Common Mistakes:
- Returning data synchronously without Promise
- Using setTimeout without Promise
- Returning timeout ID instead of data
3. Given this mock fetch function in Next.js:
What will be logged to the console?
async function fetchData() {
return new Promise(resolve => setTimeout(() => resolve({ users: ["Alice", "Bob"] }), 500));
}
fetchData().then(data => console.log(data.users));What will be logged to the console?
medium
Solution
Step 1: Understand the Promise resolution
The function returns a Promise that resolves after 500ms with an object containing users array.Step 2: Check the then callback
The then callback logs data.users, which is ["Alice", "Bob"].Final Answer:
["Alice", "Bob"] -> Option CQuick Check:
Promise resolves to users array logged [OK]
Hint: Promise.then logs resolved data, not the Promise itself [OK]
Common Mistakes:
- Expecting immediate data without waiting
- Logging the Promise object instead of resolved value
- Confusing function call with undefined
4. Identify the error in this mock data fetch function:
async function fetchData() {
setTimeout(() => {
return { data: [1, 2, 3] };
}, 1000);
}medium
Solution
Step 1: Analyze return behavior
The function does not return anything; setTimeout callback's return is ignored.Step 2: Understand async function expectations
Async functions should return a Promise; here, no Promise is returned, so caller gets undefined.Final Answer:
The function does not return a Promise, so data is undefined -> Option BQuick Check:
Async function must return Promise, not just use setTimeout [OK]
Hint: Return a Promise to deliver data after delay [OK]
Common Mistakes:
- Assuming setTimeout return affects function return
- Thinking async forbids setTimeout
- Ignoring that async functions return Promises
5. You want to mock fetching user profiles with a delay and filter out users with empty names. Which code correctly mocks this in Next.js?
hard
Solution
Step 1: Identify filtering and delay
async function fetchUsers() { const users = [{ name: "", id: 1 }, { name: "Eve", id: 2 }]; return new Promise(resolve => setTimeout(() => resolve(users.filter(u => u.name)), 1000)); } filters out users with empty names and returns a Promise resolving after 1 second.Step 2: Check other options
A returns unfiltered data with delay, B performs filtering but is synchronous and non-async without delay, C returns filtered data synchronously without delay.Final Answer:
async function fetchUsers() { const users = [{ name: "", id: 1 }, { name: "Eve", id: 2 }]; return new Promise(resolve => setTimeout(() => resolve(users.filter(u => u.name)), 1000)); } -> Option AQuick Check:
Filter then delay with Promise = async function fetchUsers() { const users = [{ name: "", id: 1 }, { name: "Eve", id: 2 }]; return new Promise(resolve => setTimeout(() => resolve(users.filter(u => u.name)), 1000)); } [OK]
Hint: Filter data before resolving Promise with delay [OK]
Common Mistakes:
- Not filtering data before resolving
- Returning data synchronously without delay
- Using non-async functions for async behavior
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
