Created
September 8, 2019 13:50
-
-
Save pflevy/3ab3668b062812252f7d0c0a8279774d to your computer and use it in GitHub Desktop.
Creating custom react hooks. Real-time firebase database entry listener example. Custom hook file.
This file contains 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 { useEffect, useState } from "react"; | |
import firebase from "./database"; | |
export const useDatabaseEntry = entry => { | |
const [data, setData] = useState([]); | |
useEffect(() => { | |
const ref = firebase.database().ref(entry); | |
ref.on("value", snapshot => { | |
const array = []; | |
// For each data in the entry | |
snapshot.forEach(el => { | |
// Push the object to the array | |
// If you also need to store the unique key from firebase, | |
// You can use array.push({ ...el.val(), key: el.key }); | |
array.push(el.val()); | |
}); | |
setData(array); | |
}); | |
// Clean-up function | |
return () => ref.off("value"); | |
}, [entry]); | |
return data; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
can you fix