Skip to content

Instantly share code, notes, and snippets.

@ankit-kumar-jat
Last active June 15, 2023 18:10
Show Gist options
  • Save ankit-kumar-jat/a6e02fb0ddc4d50473eefbcb8607668b to your computer and use it in GitHub Desktop.
Save ankit-kumar-jat/a6e02fb0ddc4d50473eefbcb8607668b to your computer and use it in GitHub Desktop.
Axios Base Query for RTK Query (redux toolkit)
import axios from 'axios'
export const axiosBaseQuery =
({ baseUrl, prepareHeaders }) => {
return async ({ url, method, body: data, params, ...rest }, api) => {
try {
// this to allow prepare headers
if (prepareHeaders) {
axios.interceptors.request.use(function (config) {
const newHeaders = prepareHeaders(config.headers, api);
config.headers = { ...config.headers, ...newHeaders }
return config;
})
}
const result = await axios({ url, baseURL: baseUrl, method, data, params, ...rest, signal: api.signal })
return {
data: result.data,
meta: {
headers: result.headers,
status: result.status,
config: result.config,
request: result.request,
}
}
} catch (axiosError) {
let err = axiosError
return {
error: {
status: err.response?.status,
data: err.response?.data || err.message,
headers: err.response?.headers
},
}
}
}
}
export default axiosBaseQuery
@DementedEarplug
Copy link

DementedEarplug commented Jun 15, 2023

Do you have an example of how to use the prepareHeaders with this axiosBaseQuery? I keep getting headers.set is not a fucntion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment