0
0
NextJSframework~5 mins

Mocking data fetching in NextJS

Choose your learning style9 modes available
Introduction

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.

You want to build a page before the real API is ready.
You want to test how your app behaves with different data.
You want to avoid slow or unreliable network calls during development.
You want to show a loading state or error state without real data.
You want to practice fetching data without setting up a backend.
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
Returns mock user data immediately without delay.
NextJS
async function fetchUser() {
  return { id: 1, name: 'Alice' };
}
Simulates a 500ms delay before returning a list of posts.
NextJS
async function fetchPosts() {
  await new Promise(r => setTimeout(r, 500));
  return [{ id: 1, title: 'Hello' }, { id: 2, title: 'World' }];
}
Simulates a failed fetch to test error handling.
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>
  );
}
OutputSuccess
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.