T
TanStack2y ago
stormy-gold

Using react-query with Axios and intercepting requests and responses

Does anyone have a good example of using react-query with Axios and intercepting requests and responses? I googled it quite a bit and couldn't find any good examples. I am using react-query for the first time. From the tutorials I've looked it, it seems pretty straight forward for basic use cases. Just struggling with this example.
2 Replies
intense-chocolate
intense-chocolate2y ago
What is your use case?
fair-rose
fair-rose2y ago
A basic example would look like this:
import axios from "axios";

// Create an instance of Axios
const myAxios = axios.create();

// Add a request interceptor
myAxios.interceptors.request.use((config) => {
// Do something with the request config
// Like update the baseURL in the request config
config.baseURL = "http://My.Base.URL";

return config;
});

// Add a response interceptor
myAxios.interceptors.response.use(async (response) => {
// Do something with the response

return response;
});

const getData = async () => {
let response = await myAxios.get(MY_URI);

return response.data;
};

export const useGetDataQuery = () => {
return useQuery({
queryKey: ["my_data"],
queryFn: () => getData()
});
};
import axios from "axios";

// Create an instance of Axios
const myAxios = axios.create();

// Add a request interceptor
myAxios.interceptors.request.use((config) => {
// Do something with the request config
// Like update the baseURL in the request config
config.baseURL = "http://My.Base.URL";

return config;
});

// Add a response interceptor
myAxios.interceptors.response.use(async (response) => {
// Do something with the response

return response;
});

const getData = async () => {
let response = await myAxios.get(MY_URI);

return response.data;
};

export const useGetDataQuery = () => {
return useQuery({
queryKey: ["my_data"],
queryFn: () => getData()
});
};

Did you find this page helpful?