NuxtN
Nuxt2y 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 };
  }

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 };
  }

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?
Was this page helpful?