Skip to content

Instantly share code, notes, and snippets.

@rimzzlabs
Last active September 28, 2023 15:13
Show Gist options
  • Save rimzzlabs/edaedc3d1f19b47029f4e30f20d37c92 to your computer and use it in GitHub Desktop.
Save rimzzlabs/edaedc3d1f19b47029f4e30f20d37c92 to your computer and use it in GitHub Desktop.
import { axios } from 'axios'
import type { AxiosError } from 'axios'
const asyncFetch = async <T = unknown>(url: string, config?: ExtendConfig) => {
try {
const res = await axios<T>({
url,
...config,
})
return [res.data as T, null] as const
} catch (e) {
return [null, e as AxiosError<T>] as const
}
}
// usage
import { type TUser } from '@/types/user'
export async function getUser(){
const [res, err] = await asyncFetch<TUser>({
url: "https://api.com/api/v1/user",
headers: {
"Content-Type": "application/json"
}
})
if(err) return null
return res.data
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment