N
Nuxt5mo ago
Mike

Adding a watcher inside `useAsyncData`

Hi. I've wrapped useAsyncData in order to add some error handling:
async function myAsyncData<T>(...args: AsyncArgs<T>) {
const { error, ...rest } = await useAsyncData<T>(...args);
return { error: computed(() => humanReadableError(error)), ...rest };
}
async function myAsyncData<T>(...args: AsyncArgs<T>) {
const { error, ...rest } = await useAsyncData<T>(...args);
return { error: computed(() => humanReadableError(error)), ...rest };
}
However now I want to submit an error to sentry in case of errors. If I use error.value inside myAsyncData, i'll lose reactivity so I don't want to do that. However I can add a watcher on error and that seems to work:
async function myAsyncData<T>(...args: AsyncArgs<T>) {
const { error, ...rest } = await useAsyncData<T>(...args);
watch(error, () => {
console.error(error);
// Error reporting here
});
return { error: computed(() => humanReadableError(error)), ...rest };
}
async function myAsyncData<T>(...args: AsyncArgs<T>) {
const { error, ...rest } = await useAsyncData<T>(...args);
watch(error, () => {
console.error(error);
// Error reporting here
});
return { error: computed(() => humanReadableError(error)), ...rest };
}
However something about this approach seems wrong to me. Is using a watcher like this bad practice? If not, do I need to manually unsubscribe the watcher on unMount? Is there a better way to do this?
2 Replies
Mähh
Mähh5mo ago
When the goal is to send something to your monitoring in case of failed fetch, whats about creating a own fetch instance for it?
export const $myCustomFetch = $fetch.create({
onRequestError(context) {
// send error to monitoring service api
}
})
export const $myCustomFetch = $fetch.create({
onRequestError(context) {
// send error to monitoring service api
}
})
<script setup lang="ts">
const {data} = await useAsyncData('my-key', async () => $myCustomFetch('/foo'))
</script>
<script setup lang="ts">
const {data} = await useAsyncData('my-key', async () => $myCustomFetch('/foo'))
</script>
Mike
MikeOP5mo ago
Good point, I think I'll do this. I have to intercept onResponseError but this works. Thank you! 🙂
Want results from more Discord servers?
Add your server