vue-swr-plus
Version:
SWR (stale-while-revalidate) for Vue
31 lines (26 loc) • 657 B
text/typescript
import { ref, watchEffect, Ref } from 'vue'
interface SWROptions {
fetcher: (...args: any[]) => Promise<any>
initialData?: any
}
export function useSWR(key: string, options: SWROptions) {
const data = ref(options.initialData)
const error = ref<Error | null>(null)
const isValidating = ref(false)
watchEffect(async () => {
isValidating.value = true
try {
const result = await options.fetcher(key)
data.value = result
} catch (err) {
error.value = err as Error | null
} finally {
isValidating.value = false
}
})
return {
data,
error,
isValidating
}
}