Using mirageJS with Axios in an existing application
See original GitHub issueHey, I had the idea to use the mirage as a hybrid. I mean, to test it better I’ve created a POC to test the Mirage + Axios. However, I’m facing a few problems… it seems the request went through the mirage but it never reaches the Axios response going always to the final bracket.
I did the POC because I started using it in a big project, and we faced it, and I did not know how to conduct it.
I saw a few solutions which say to exchange the Axios per fetch. But in a big application, it could take more time than I expect. Is there a solution to work with both?
server.js
import { createServer } from "miragejs";
export function makeServer() {
return new createServer({
routes() {
this.passthrough();
this.passthrough("https://api.github.com/**");
this.namespace = "/learning";
this.urlPrefix = "http://localhost:3333";
this.get("/api/users", () => [
{ id: "1", name: "Luke" },
{ id: "2", name: "Leia" },
{ id: "3", name: "Anakin" },
]);
},
});
}
App.js
import { useEffect, useState } from "react";
import { api } from "./axios";
import { makeServer } from "./server";
interface UserProps {
avatar: string;
blog: string;
name: string;
}
interface UserFactProps {
name: string;
id: number;
}
function App() {
const [user, setUser] = useState<UserProps>({} as UserProps);
const [factUser, setFactUser] = useState<UserFactProps[]>([]);
makeServer();
useEffect(() => {
try {
api.get("/users/michenriq").then((response) => {
setUser({
avatar: response.data.avatar_url,
blog: response.data.blog,
name: response.data.name,
});
});
} catch (err) {
console.warn(err);
console.warn("parou aqui");
} finally {
console.log("caiu aqui");
}
api.get("http://localhost:3333/learning/api/users").then((response) => {
setFactUser(response.data);
});
}, []);
return (
<>
<h1>{user.name}</h1>
<p>{user.blog}</p>
<img src={user.avatar} alt={user.name} />
{factUser?.map((user) => {
return <p key={user.id}>{user.name}</p>;
})}
</>
);
}
export default App;
axios instance ps: I put the interceptors to understand how far the request gone
import axios, { Axios } from 'axios'
export const api: Axios = axios.create({
baseURL: 'https://api.github.com'
})
I can do it using hybrid fetch to external api and axios to internal, but I figure it does not the right way to do that.
ps: these 3 items are the mirage mock not the GitHub api, tough
As the images below the request is made but we never got the response…
Issue Analytics
- State:
- Created 2 years ago
- Comments:17
Top GitHub Comments
I have the same problem
Same issue. It works good with Fetch API, but doesn’t work with axios (tested on axios@0.24.0 and mirage@0.1.42).
It works good with mirage@0.1.41