Skip to content
This repository was archived by the owner on Dec 5, 2024. It is now read-only.

Commit c45177f

Browse files
committed
feat: return $fetch and $fetchState from useFetch
These are also accessible from `useContext`.
1 parent 796258f commit c45177f

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

docs/helpers/useFetch.md

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,16 @@ export default defineComponent({
1515
setup() {
1616
const name = ref('')
1717

18-
useFetch(async () => {
18+
const { $fetch, $fetchState } = useFetch(async () => {
1919
name.value = await axios.get('https://myapi.com/name')
2020
})
2121

22+
// Manually trigger a refetch
23+
$fetch()
24+
25+
// Access fetch error, pending and timestamp
26+
$fetchState
27+
2228
return { name }
2329
},
2430
})

src/fetch.ts

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,11 @@ export const useFetch = (callback: Fetch) => {
144144
}
145145
})
146146

147-
if (process.server || !isSsrHydration(vm)) return
147+
if (process.server || !isSsrHydration(vm))
148+
return {
149+
$fetch: vm.$fetch,
150+
$fetchState: vm.$fetchState,
151+
}
148152

149153
// Hydrate component
150154
vm._hydrated = true
@@ -154,7 +158,11 @@ export const useFetch = (callback: Fetch) => {
154158
// If fetch error
155159
if (data && data._error) {
156160
vm.$fetchState.error = data._error
157-
return
161+
162+
return {
163+
$fetch: vm.$fetch,
164+
$fetchState: vm.$fetchState,
165+
}
158166
}
159167

160168
onBeforeMount(() => {
@@ -169,4 +177,9 @@ export const useFetch = (callback: Fetch) => {
169177
}
170178
}
171179
})
180+
181+
return {
182+
$fetch: vm.$fetch,
183+
$fetchState: vm.$fetchState,
184+
}
172185
}

0 commit comments

Comments
 (0)