pinia+track
This commit is contained in:
31
src/pocketbase/collection.ts
Normal file
31
src/pocketbase/collection.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
|
||||
import { usePocketBase } from "@/pocketbase";
|
||||
import { RecordModel, RecordSubscription, UnsubscribeFunc } from "pocketbase";
|
||||
import { Ref, computed, onMounted, onUnmounted, ref } from "vue";
|
||||
|
||||
export const watchCollection = <T extends RecordModel = RecordModel>(collection: string, query: string, callback: (data: RecordSubscription<T>) => void) => {
|
||||
const pb = usePocketBase();
|
||||
let unsubscribe: UnsubscribeFunc = () => Promise.resolve();
|
||||
|
||||
onMounted(async () => {
|
||||
unsubscribe = await pb.collection(collection).subscribe<T>(query, callback);
|
||||
});
|
||||
onUnmounted(() => unsubscribe());
|
||||
};
|
||||
|
||||
export const useCollection = <T extends RecordModel = RecordModel>(collection: string) => {
|
||||
const pb = usePocketBase();
|
||||
const list = ref<T[]>([]) as Ref<T[]>;
|
||||
|
||||
watchCollection<T>(collection, '*', data => {
|
||||
if (data.action === 'delete') {
|
||||
list.value = list.value.filter(i => i.id !== data.record.id);
|
||||
} else if (data.action === 'update') {
|
||||
list.value = list.value.map(i => i.id === data.record.id ? data.record : i);
|
||||
} else if (data.action === 'create') {
|
||||
list.value = [...list.value, data.record];
|
||||
}
|
||||
});
|
||||
onMounted(async () => list.value = await pb.collection(collection).getFullList<T>().catch(() => [] as T[]));
|
||||
return computed(() => list.value);
|
||||
}
|
||||
Reference in New Issue
Block a user