use-firebase
A React hook for importing firebase dynamically.
The problem
Us web developers want speedy performance, so we use code-splitting to make firebase be loaded in after the main part of the appliaction. Lazy-loading the firebase module is the solution, but it is a bit tricky to implement without being extremely verbose.
The solution
The use-firebase
package allows you to lazy-load firebase without the code being ugly.
Example
import React from 'react'
import useFirebase from 'use-firebase'
var firebaseConfig = {
apiKey: 'AIzaSyDOCAbC123dEf456GhI789jKl01-MnO',
// ...
}
export default () => {
const firebase = useFirebase(firebaseConfig)
const [data, setData] = React.useState(null)
// Get data on mount
React.useEffect(() => {
if (firebase) {
firebase
.firestore()
.doc('a/document')
.get()
.then((res) => {
setData(res)
})
}
}, [])
return <div>{data ? JSON.stringify(data) : <p>Loading</p>}</div>
}
Installation
npm install --save @penguoir/use-firebase
Api
Typedefs
-
FirebaseConfig :
Object
-
callback :
function
-
Callback function for when firebase is initialized
-
callback ⇒
firebase.app.App
|null
-
useFirebase - Load firebase with a hook
Object
FirebaseConfig : Kind: global typedef
Properties
Name | Type |
---|---|
apiKey | string |
authDomain | string |
databaseURL | string |
projectId | string |
storageBucket | string |
messagingSenderId | string |
appId | string |
measurementId | string |
function
callback : Callback function for when firebase is initialized
Kind: global typedef
Param | Type | Description |
---|---|---|
FirebaseApp | firebase.app.App |
The firebase app, no need to .initializeApp() here! Just use this if you want custom settings |
firebase.app.App
| null
callback ⇒ useFirebase - Load firebase with a hook
Kind: global typedef
Returns: firebase.app.App
| null
- Firebase app OR NULL (when loading)
Param | Type | Description |
---|---|---|
FirebaseConfig | FirebaseConfig |
Firebase config |
Example
const firebase = useFirebase({ appid: whatever })
// ... later, e.g. in a component ...
React.useEffect(() => {
if (firebase) {
firebase
.firestore()
.doc('a/doc')
.get()
.then((res) => set)
}
}, [])