Search code examples
vue.jsvuejs2vue-composition-apivue-apollo

vue apollo useQuery, how to return the result?


I'm trying to use useQuery with Vue 2 using @vue/apollo-composable.

This is my setup function:

setup(props,ctx){
  const product = ref(null);
  const param = usePram();
  const currentProduct = computed(()=>product?.value?.prop || {nope:true};
  const getProduct = () => {
    if(sku.value){
      product.value = provideApolloClient(apolloClient)(() => useQuery(
        gql`the query`,
        {
          param: param.value,
        }
      )).result;
    }
  };
  watch(
    [param],
    ()=>{
      getProduct();
    }
  );
  watch(product,()=>{
    //product.value.value is undefined now
    console.log('product changed:',product.value,product.value?.value)
    //later when I run window.product.value.product.id in the console
    //  I get the id of the product
    window.product = product.value;
  })
  onMounted(getProduct);
  return { currentProduct:currentProduct.value }
},

The template:

<div class="row no-gutters">
  <pre>{{JSON.stringify(currentProduct,undefined,2)}}</pre>
</div>

It only shows {nope: true} and the watch on product execute only once saying product.value?.value is undefined but running window.product.value.product.id gives me the product id so I guess when it logs it isn't set yet and when it sets it is no longer running the watch.

I'm wondering how to get the product value out of the watch that watches arg and return it so I can use it in the view.


Solution

  • Try to add deep:true option since the watched property is an object:

      watch(product,()=>{
        //product.value.value is undefined now
        console.log('product changed:',product.value,product.value?.value)
        //later when I run window.product.value.product.id in the console
        //  I get the id of the product
        window.product = product.value;
      },{deep:true})