Last active
December 24, 2024 19:58
-
-
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 hidden or 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
Type '{ [x: string]: any; Accept?: AxiosHeaderValue | undefined; "Content-Length"?: AxiosHeaderValue | undefined; "User-Agent"?: AxiosHeaderValue | undefined; "Content-Encoding"?: AxiosHeaderValue | undefined; Authorization?: AxiosHeaderValue | undefined; 'Content-Type'?: ContentType | undefined; }' is not assignable to type 'AxiosRequestHeaders'.
Type '{ [x: string]: any; Accept?: AxiosHeaderValue | undefined; "Content-Length"?: AxiosHeaderValue | undefined; "User-Agent"?: AxiosHeaderValue | undefined; "Content-Encoding"?: AxiosHeaderValue | undefined; Authorization?: AxiosHeaderValue | undefined; 'Content-Type'?: ContentType | undefined; }' is missing the following properties from type 'AxiosHeaders': set, get, has, delete, and 23 more.ts(2322)