Created
April 16, 2021 13:02
-
-
Save movibe/2863e443eba0fffd9b6c66adfb8acfd7 to your computer and use it in GitHub Desktop.
useSWRAxios
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, { 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