Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

244
Views
how to fetch data from mock api in react?

I am using https://www.npmjs.com/package/axios-mock-adapter to fetch mock response .but I am not able to get mock response.

here is my code https://codesandbox.io/s/frosty-surf-g9tezx?file=/src/App.js

here I am fetching actual data

React.useEffect(() => {
  const a = async function () {
    const ab = await axios.get("https://jsonplaceholder.typicode.com/todos/1");
    console.log(ab);
  };
  a();
}, []);

using axios adaptor I mock API

// This sets the mock adapter on the default instance
var mock = new MockAdapter(axios);

// Mock any GET request to /users
// arguments for reply are (status, data, headers)
mock.onGet("https://jsonplaceholder.typicode.com/todos/1").reply(200, {
  users: [{ id: 1, name: "John Smith" }],
});

I need instead of actual request it will get mock response or in other words I can toggle my option sometimes it goes to actual request or some time it goes from mock api

about 4 years ago ยท Juan Pablo Isaza
1 answers
Answer question

0

You seem to be missing something like import "./mockAPI". Right now, nothing imports your mock setup script so it never runs.

I would set it up like this where you create an Axios instance for your app to use and conditionally apply the mock adapter based on an environment variable

// api.js
import axios from "axios";
import MockAdapter from "axios-mock-adapter";

const api = axios.create({
  baseURL: process.env.REACT_APP_API_BASE
});

export const mock = new MockAdapter(api);

if (process.env.REACT_APP_MOCK_API === "true") {
  mock.onGet("/todos/1").reply(200, {
    users: [{ id: 1, name: "John Smith" }]
  });
} else {
  mock.restore();
}

export default api;

With a .env file like

REACT_APP_API_BASE=https://jsonplaceholder.typicode.com/
REACT_APP_MOCK_API=true

Then import the Axios instance from api.js instead of using axios directly.

// import axios from "axios"; ๐Ÿ‘ˆ not this
import api from "./api";

// ...

useEffect(() => {
  api.get("/todos/1").then(({ data }) => {
    console.log(data);
  });
}, []);

You can have different .env files for different configurations

about 4 years ago ยท Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!