Skip to content

Commit

Permalink
feat: return $fetch and $fetchState from useFetch
Browse files Browse the repository at this point in the history
These are also accessible from `useContext`.
  • Loading branch information
danielroe committed May 9, 2020
1 parent 796258f commit c45177f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
8 changes: 7 additions & 1 deletion docs/helpers/useFetch.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,16 @@ export default defineComponent({
setup() {
const name = ref('')

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

// Manually trigger a refetch
$fetch()

// Access fetch error, pending and timestamp
$fetchState

return { name }
},
})
Expand Down
17 changes: 15 additions & 2 deletions src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,11 @@ export const useFetch = (callback: Fetch) => {
}
})

if (process.server || !isSsrHydration(vm)) return
if (process.server || !isSsrHydration(vm))
return {
$fetch: vm.$fetch,
$fetchState: vm.$fetchState,
}

// Hydrate component
vm._hydrated = true
Expand All @@ -154,7 +158,11 @@ export const useFetch = (callback: Fetch) => {
// If fetch error
if (data && data._error) {
vm.$fetchState.error = data._error
return

return {
$fetch: vm.$fetch,
$fetchState: vm.$fetchState,
}
}

onBeforeMount(() => {
Expand All @@ -169,4 +177,9 @@ export const useFetch = (callback: Fetch) => {
}
}
})

return {
$fetch: vm.$fetch,
$fetchState: vm.$fetchState,
}
}

1 comment on commit c45177f

@vercel
Copy link

@vercel vercel bot commented on c45177f May 9, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.