Last active
June 15, 2023 18:10
-
-
Save ankit-kumar-jat/a6e02fb0ddc4d50473eefbcb8607668b to your computer and use it in GitHub Desktop.
Axios Base Query for RTK Query (redux toolkit)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do you have an example of how to use the prepareHeaders with this axiosBaseQuery? I keep getting
headers.set
is not a fucntion.