[Vuejs]-Vue Composition API: Init variable in mounted back to setup

2👍

const product = reactive({});

product shuld be ref and not reactive, because I reassign the entire object.

When product is reassigned to response.data which is the new object so it no longer references the old reactive object anymore.
See more here.

1👍

When you’re using reactive you don’t have .value but if you use ref you the value is inside .value. So your composable must be like:

export default function useProduct() {
     const product = ref();
    
   async function getProduct(id) {
     try{ 
       const response = await {{http Request}}
       product.value = response.data; // it is a single object
     }catch(err) {
       console.log(err);
     }
   } 
    return {product, getProduct}
}

If you use Nuxt 3, you must use useState instead of ref doc

👤Farid

Leave a comment