How to await new data after switching dataSource in useDocument
?
#1451
-
Howdy! I'm trying to contain vuefire inside of Pinia store. I want to fetch single document and await for it, to check if it exists, then act accordingly.
beforeEnter: async (to) => {
const objectStore = useObjectStore();
if (!(await objectStore.fetch(String(to.params.objectId)))) {
return {
name: 'not_found',
params: {
pathMatch: to.path.substring(1).split('/'),
},
query: to.query,
hash: to.hash,
};
}
} So far, so good! Yet, having Pinia store kinda forces us to keep data refs constant, fortunately we can use export const useObjectStore = defineStore('objectStore', () => {
const db = useFirestore();
const objectsRef = collection(db, 'objects');
const object = ref<Obj | null>(null);
return {
object,
fetch: async (objectId: string): Promise<Obj | null> => {
const { promise } = useDocument(() => doc(objectsRef, objectId), { target: object });
await promise;
return object.value;
},
};
}); But unfortunately we receive following console warning:
That's fair, but the problem is - using reactive value detaches our control of when we can await for new data. My current workaround is to send different request to check for object existence, and then use reactive flow as normal. It's not ideal, but it works. My question is: How I can change data source and await the changes? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Composables must be at the top level. So it becomes: export const useObjectStore = defineStore('objectStore', () => {
const db = useFirestore();
const objectsRef = collection(db, 'objects');
const currentObjectId = ref(0) // or maybe from the route?
const { promise, data: object } = useDocument<Obj>(() => doc(objectsRef, currentObjectId.value));
async fetchObject(objectId: string) {
currentObjectId.value = objectId
await nextTick() // from vue, we need to wait for changes to propagate
await promise.value
return object.value
}
return {
object,
fetchObject,
};
}); |
Beta Was this translation helpful? Give feedback.
Composables must be at the top level. So it becomes: