Skip to content

Instantly share code, notes, and snippets.

@zero-is-one
Forked from jherr/atomWithCollection.ts
Last active August 14, 2024 18:56
Show Gist options
  • Save zero-is-one/caaaf44561d428faf03e6ee6ef6e9bea to your computer and use it in GitHub Desktop.
Save zero-is-one/caaaf44561d428faf03e6ee6ef6e9bea to your computer and use it in GitHub Desktop.
import {
CollectionReference,
doc,
onSnapshot,
setDoc,
} from "firebase/firestore";
import { WritableAtom, atom } from "jotai";
function atomWithCollection<T>(
collection: CollectionReference<T>,
): WritableAtom<T[], [string, T], void> {
const dataAtom = atom<T[]>([]);
dataAtom.onMount = (dispatch) =>
onSnapshot(collection, (snapshot) => {
dispatch(snapshot.docs.map((doc) => doc.data() as T));
});
return atom(
(get) => {
return get(dataAtom);
},
(_get, _set, id, data) => {
setDoc(doc(collection, id), data);
},
);
}
export default atomWithCollection;
@zero-is-one
Copy link
Author

This uses the firebase v9 SDK

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment