rival-black
rival-black3w ago

Access axios instance used to create data provider

Is there a way to access the axios instance that I used in the creation of my data provider elsewhere in the code? I need to manually submit an axios request, and I want access to the interceptors I setup when creating the dataProvider that's registered to <Refine>.
2 Replies
kapa.ai
kapa.ai3w ago
Hi @Hypnotic Meat. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- Yes, you can access the axios instance used to create your data provider elsewhere in your code. Here's how you can do it: 1. When creating your data provider, export the axios instance:
import axios from "axios";

export const axiosInstance = axios.create();

// Set up your interceptors here
axiosInstance.interceptors.request.use(/* ... */);
axiosInstance.interceptors.response.use(/* ... */);

export const dataProvider = DataProvider("API_URL", axiosInstance);
import axios from "axios";

export const axiosInstance = axios.create();

// Set up your interceptors here
axiosInstance.interceptors.request.use(/* ... */);
axiosInstance.interceptors.response.use(/* ... */);

export const dataProvider = DataProvider("API_URL", axiosInstance);
2. Then, in your components or other parts of your code where you need to make manual axios requests, you can import and use this axios instance:
import { axiosInstance } from "./dataProvider";

// Use axiosInstance to make your manual request
const response = await axiosInstance.get("/some-endpoint");
import { axiosInstance } from "./dataProvider";

// Use axiosInstance to make your manual request
const response = await axiosInstance.get("/some-endpoint");
This approach is demonstrated in the Simple REST data provider documentation, where they show how to create and use a custom axios instance:
import { Refine } from "@refinedev/core";
import dataProvider from "@refinedev/simple-rest";
import axios from "axios";

const httpClient = axios.create();

const App = () => {
return (
<Refine
// `httpClient` is optional.
dataProvider={(dataProvider("<API_URL>"), httpClient)}
/* ... */
/>
);
};
import { Refine } from "@refinedev/core";
import dataProvider from "@refinedev/simple-rest";
import axios from "axios";

const httpClient = axios.create();

const App = () => {
return (
<Refine
// `httpClient` is optional.
dataProvider={(dataProvider("<API_URL>"), httpClient)}
/* ... */
/>
);
};
By exporting and reusing the same axios instance, you ensure that all your requests, whether they go through the data provider or are made manually, use the same configuration and interceptors. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai3w ago
<@224018850419572736> Kapa.ai is still learning and improving, please let me know how I did by reacting below.

Did you find this page helpful?