Created
February 5, 2022 15:32
-
-
Save kazuooooo/de64cec0db4fcffbcc8815e87cbbf320 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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