Search code examples
nuxt.jsapollo-clientnuxt3.jsvue-apollocomposable

Nuxt - Component is already mounted, please use $fetch instead


I have this code

const redirectToPayment = async () => {
  const { data } = await useAsyncQuery(
    createCheckoutMutation,
    { variantId: product.value.productByHandle.variants.edges[0].node.id}
  );

  window.location.href = data.value.checkoutCreate.checkout.webUrl;
}

I am getting the next warning

[nuxt] [useAsyncData] Component is already mounted, please use $fetch instead. See https://nuxt.com/docs/getting-started/data-fetching

I've been searching and reading and it seems the solution it's here, but I can't make it work in my example. Could anyone help me? Thanks

Edit/update from @Connor answer I have tried moving the request outside de click (event handler) and I still receive the same warning

const data = await $fecth(
    createCheckoutMutation,
    { variantId: product.value.productByHandle.variants.edges[0].node.id}
  );

Solution

  • useAsyncData (and by extension useAsyncQuery) is a composable, which means it can only be called at the top level of a setup function. You cannot call it within an event handler.

    When making requests within an event handler in Nuxt, $fetch is the correct approach.

    You can read more about data fetching in Nuxt here.

    I'm not familiar with Nuxt Apollo, but what you probably want to do is call useApollo in your setup function to get a handle on an apollo client and use that client in your handler function.