Skip to content

Instantly share code, notes, and snippets.

@kazuooooo
Created February 5, 2022 15:32
Show Gist options
  • Save kazuooooo/de64cec0db4fcffbcc8815e87cbbf320 to your computer and use it in GitHub Desktop.
Save kazuooooo/de64cec0db4fcffbcc8815e87cbbf320 to your computer and use it in GitHub Desktop.
import { CollectionReference, DocumentReference, onSnapshot, Query, Unsubscribe } from "firebase/firestore";
import { PiniaPluginContext } from "pinia";
export const PiniaFirestoreSync = ({ store }: PiniaPluginContext) => {
store.sync = (key, ref) => {
// Document
if (ref instanceof DocumentReference) {
return onSnapshot(ref, (ds) => {
if (ds.exists()) {
store.$patch({ [key]: ds.data() })
}
})
}
// Collection or Query
return onSnapshot(ref, (qs) => {
const datum = qs.docs.map(d => d.data())
store.$patch((state) => {
state[key] = datum
})
})
}
}
declare module 'pinia' {
export interface PiniaCustomProperties<Id, S, G, A> {
sync(key: string, ref: DocumentReference): Unsubscribe
sync(key: string, ref: CollectionReference): Unsubscribe
sync(key: string, ref: Query): Unsubscribe
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment