Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

245
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda