-
Notifications
You must be signed in to change notification settings - Fork 342
Closed
Labels
Description
How to update/merge ref with another ref?
I'll explain by this example:
I create a useProduct
function gets an argument and return a ref base of that argument:
const useProduct = (productId) => {
insertToTheStoreAsync(axios.get(`/api/products/${productId}`)); // not really but lets say it make a http call and insert to the global store.
const items = computed(() => { return fromTheStore.get(productId)... });
return { items }
}
In my component I have a setup function which I invoke useData
:
setup() {
const productId = 1;
const { items } = useProduct(productId);
return { items };
}
Which works great.
But I want to get the productId from the props. and here the problem is. seince the props.productId is expected to change (data binding) so I need to use watch and then call the useProduct
function.
The problem is I already declare the items so in the setup scope. and I need to change it in the watch scope.
setup(props) {
const items = ref(null);
watch(() => props.productId, (v) => {
if (!v) return;
const { items } = useProduct(productId); // <-- can't do it, the items is declared.
});
return { items }
}
How can I solve this?
edit
Here for example I use promise (simulate a http call): (the problem is not promise but the way of how vue composition api works)
const useProductApi = ({ productId }) => {
const api = (p, ms) => new Promise((resolve) => setTimeout(resolve({ p, items: [{ id: 1 }, { id: 2 }] }), ms));
const productApi = usePromise(() =>
Promise.all([ api(productId, 5000) ]).then(r => /*** INSERT r TO THE STORE ***/)
);
return productApi;
};
const useProduct = (productId) => {
const product = useProductApi({ productId });
product.exec();
const items = computed(() => { return fromTheStore.get(productId)... });
return { items }
}