Last active
August 14, 2024 18:55
-
-
Save jherr/2558129a9daf4ff3520b5d36e79d44fc to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { 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