How to Use Mock Data in React.js with APIDog

Using mock data is a powerful technique to ensure your React.js application is robust and reliable, even before the actual backend is ready, and this guide we'll learn more about it.

Iroro Chadere

Iroro Chadere

15 May 2025

How to Use Mock Data in React.js with APIDog

In modern web development, React.js applications often rely on APIs for data. However, what happens when these APIs aren't ready or available during development? This is where API mocking becomes crucial. By using tools like Apidog, developers can simulate API responses, enabling efficient development and testing.

This guide will walk you through the process of using mock data in your React.js projects with Apidog, ensuring smooth development even when backend services are unavailable.

What is Mock API in React JS?

API mocking involves creating a simulated version of an API that mimics the behavior of a real API. This mock API can return predefined responses, allowing developers to work independently of the actual API. By using mock APIs, developers can continue building and testing their applications without delays.

Should you mock API tests for React JS? What Are the Benefits?

Setting Up Apidog with Mock Data for React Project

Apidog is a powerful API design, testing, and mocking tool. With it, you can mock or generate realistic data that you can customize or edit to suit your needs.

"Apidog Mock vs other tools"

Step 1. Create an Apidog Account

To get started, you can use the web version of Apidog, you can download Apidog onto your machine to start the mocking.

button

Step 2. Create a New Project

Once you've created your account, the next step will be for you to create a new project. Projects are like folders, which keep all your files in one place. Create a new Project using the following example;

How to Mock Rest API in React with APIDog: Create a New Project
How to Mock Rest API in React with APIDog: type the name of the project

While creating your project, Apidog provides some examples that you can instantly use. Make sure to check the 'Including Examples" box so that those examples will be generated for you. Once you're done with that, click on the Create button, and tada!!!!! You're now all set!

Step 3. Configure Mock API Endpoints

The dummy data that Apidog generated for us is already packed with API specifications, data, and all of the things we need to test it.  

How to Mock Rest API in React with APIDog: Configure Mock API Endpoints

You can edit these API, play around with the settings of this project, & change a few things. When you're done, let's hit the Run button.

Step 4. Test Your Mock API

If you hit the Run button at the top of the screen, you'll likely see a little popup close to it that asks you to create an environmental variable :)

How to Mock Rest API in React with APIDog: Select Environment

Step 5. Enable Local Mock Server

Click on the select Environment variable and select Local Mock. With Local Mock you can use the local URL provided by Apidog to test your data.

How to Mock Rest API in React with APIDog:Enable Local Mock Server

Using Mock Data in a React.js Application

Now, let's integrate the mock data from Apidog into a React.js application. We'll walk through a simple example of fetching user details from the mock API.

Step 1: Set Up a React Application

If you haven't already, set up a new React application using Create React App:

npx create-react-app mock-data-example
cd mock-data-example
npm start

Step 2: Create a Service to Fetch Data

Create a new file apiService.js to handle the API requests:

// src/apiService.js

const API_BASE_URL = "http://127.0.0.1:3658/m1/602173-568233-default";

export const fetchPetData = async (id) => {
  try {
    const response = await fetch(`${API_BASE_URL}/pet/${id}`);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    return data;
  } catch (error) {
    console.error("Failed to fetch pet data:", error);
    throw error;
  }
};

Step 3: Use the Mock Data in a React Component

Create a React component to fetch and display the user data:

// src/components/PetProfile.js

import React, { useEffect, useState } from "react";
import { fetchPetData } from "../apiService";

const PetProfile = ({ petId }) => {
  const [pet, setPet] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const getPetData = async () => {
      try {
        setLoading(true);
        const petData = await fetchPetData(petId);
        setPet(petData);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };

    getPetData();
  }, [petId]);

  if (loading) return <div>Loading pet data...</div>;
  if (error) return <div>Error: {error}</div>;
  if (!pet) return <div>No pet data available</div>;

  return (
    <div>
      <h2>Pet Profile</h2>
      <p>Name: {pet.name}</p>
      <p>Status: {pet.status}</p>
      {pet.photoUrls && pet.photoUrls.length > 0 && (
        <img src={pet.photoUrls[0]} alt={pet.name} style={{ maxWidth: '200px' }} />
      )}
    </div>
  );
};

export default PetProfile;

Step 4: Use the Component in Your Application

Modify the App.js file to include the UserProfile component:

// src/App.js

import React from "react";
import PetProfile from "./components/PetProfile";

function App() {
  return (
    <div className="App">
      <h1>Pet Store Mock API Demo</h1>
      <PetProfile petId="1" />
    </div>
  );
}

export default App;

Start your React application:

You can start the react application by running npm start. Your React application should now fetch and display pet data using the mock API provided by Apidog.

The full source code of the above file can be found on CodeSandBox . Make sure to clone and change the URL to your own server URL else it won't fetch!

Best Practices for API Mocking with React Apps

Best Practices for API Mocking with React Apps
Best Practices for API Mocking with React Apps
For more robust data fetching, consider using libraries like React Query or SWR. These tools provide caching, automatic refetching, and other advanced features that can enhance your application's performance and user experience.

Conclusion

Using mock data is a powerful technique to ensure your React.js application is robust and reliable, even before the actual backend is ready. By leveraging Apidog to create and manage mock APIs, you can streamline your development and testing workflows. Start using Apidog for your mock data needs and enhance your development process today.

FAQs about Mocking Rest API from React.js

Q1. How to mock REST API in React?

To mock a REST API in React, you can:

Q2. Can you make a REST API with React?

React itself is a frontend library and cannot create a REST API. However, you can:

Q3. What is mock data in React?

Mock data in React refers to fake or sample data used during development and testing. It allows developers to:

Mock data is typically stored in JSON format and can be used to populate components, test state management, and verify rendering logic.

Q4. How to create mock REST API?

To create a mock REST API:

Use JSON Server:

Use Express.js:

Use online services:

Use Mirage JS:

These methods allow you to create a functional mock API that your React application can interact with during development and testing phases.

button

Explore more

Apidog SEO Settings Explained: Maximize Your API Docs Visibility

Apidog SEO Settings Explained: Maximize Your API Docs Visibility

Discover how to supercharge your API documentation's visibility with Apidog's powerful SEO features. This comprehensive guide covers everything from page-level optimizations like custom URLs and meta tags to site-wide settings such as sitemaps and robots.txt.

18 June 2025

How to Protect API Specification from Unauthorized Users with Apidog

How to Protect API Specification from Unauthorized Users with Apidog

Learn how Apidog empowers you to protect API specification from unauthorized users. Explore advanced API documentation security, access controls, and sharing options for secure API development.

17 June 2025

How to Use the PostHog MCP Server?

How to Use the PostHog MCP Server?

Discover how to use the PostHog MCP server with this in-depth technical guide. Learn to install, configure, and optimize the server for seamless PostHog analytics integration using natural language. Includes practical use cases and troubleshooting.

16 June 2025

Practice API Design-first in Apidog

Discover an easier way to build and use APIs