Skip to content

Instantly share code, notes, and snippets.

@jcuffe
Created July 31, 2019 21:36
Show Gist options
  • Save jcuffe/3852cdc292eee94bef3060df1a7b6a35 to your computer and use it in GitHub Desktop.
Save jcuffe/3852cdc292eee94bef3060df1a7b6a35 to your computer and use it in GitHub Desktop.
Firebase hooks!
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