Skip to content

Instantly share code, notes, and snippets.

@movibe
Created April 16, 2021 13:02
Show Gist options
  • Save movibe/2863e443eba0fffd9b6c66adfb8acfd7 to your computer and use it in GitHub Desktop.
Save movibe/2863e443eba0fffd9b6c66adfb8acfd7 to your computer and use it in GitHub Desktop.
useSWRAxios
import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios'
import useSWR, { ConfigInterface } from 'swr'
export const useSWRAxios = <Data extends {}>(
request: Omit<AxiosRequestConfig, 'baseURL' | 'method' | 'data'>,
config?: ConfigInterface,
) => {
const requestModified: AxiosRequestConfig = {
...request,
method: `GET`,
}
const configModified: ConfigInterface = {
...config,
// global customizations
}
/**
* Axios has a wrapper object around data => filter response
*/
const { data: response, ...responseUseSWR } = useSWR<
AxiosResponse<Data>,
AxiosError
>(
JSON.stringify(requestModified),
async () => axios(requestModified),
configModified,
)
const { data, ...responseAxios } = response || {}
return { ...responseUseSWR, responseAxios, data }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment