Home > Enterprise >  how to fetch data from mock api in react?
how to fetch data from mock api in react?

Time:05-04

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

CodePudding user response:

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";            
  • Related