Created
July 31, 2019 21:36
-
-
Save jcuffe/3852cdc292eee94bef3060df1a7b6a35 to your computer and use it in GitHub Desktop.
Firebase hooks!
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 { useState } from "react" | |
import Firebase from "firebase" | |
const db = Firebase.firestore() | |
export const useCollection = options => { | |
const [documents, setDocuments] = useState(null) | |
if (!options.path) { | |
throw new Error("A path must be specified") | |
} | |
let ref = db.collection(options.path) | |
let add = ref.add | |
if (options.query) { | |
ref = ref.where(query) | |
} | |
ref.onSnapshot({ | |
next: snapshot => { | |
console.log(snapshot) | |
setDocuments(snapshot.docs()) | |
}, | |
error: error => console.error(error) | |
}) | |
return { documents, add } | |
} | |
export const useDocument = options => { | |
const [data, setData] = useState(null) | |
if (!options.path) { | |
throw new Error("A path must be specified") | |
} | |
const ref = db.doc(options.path) | |
const { set, update, delete: remove } = ref | |
ref.onSnapshot({ | |
next: snapshot => setData(snapshot.data()), | |
error: error => console.error(error) | |
}) | |
return { data, set, update, remove } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment