Skip to content

Instantly share code, notes, and snippets.

@ankit-kumar-jat
Last active December 24, 2024 19:58
Show Gist options
  • Select an option

  • Save ankit-kumar-jat/a6e02fb0ddc4d50473eefbcb8607668b to your computer and use it in GitHub Desktop.

Select an option

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
@ceyhun-akyol
Copy link

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)

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