Skip to content

Instantly share code, notes, and snippets.

@jherr
Last active April 4, 2021 01:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jherr/2558129a9daf4ff3520b5d36e79d44fc to your computer and use it in GitHub Desktop.
Save jherr/2558129a9daf4ff3520b5d36e79d44fc to your computer and use it in GitHub Desktop.
import { atom, WritableAtom } from "jotai";
import firebase from "firebase";
function atomWithCollection<TData>(
collection: firebase.firestore.CollectionReference
): WritableAtom<
TData[],
{
id: string;
data: TData;
}
> {
const dataAtom = atom<TData[]>([]);
dataAtom.onMount = (dispatch) =>
collection.onSnapshot((snapshot) => {
dispatch(snapshot.docs.map((doc) => doc.data() as TData));
});
return atom(
(get) => {
return get(dataAtom);
},
(_1, _2, { id, data }: { id: string; data: TData }) => {
collection.doc(id).set(data);
}
);
}
export default atomWithCollection;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment