Last active
February 11, 2021 03:59
-
-
Save prescottprue/108ce7b7827e2305b05cffad4cf9ca55 to your computer and use it in GitHub Desktop.
Custom hook which makes use of reactfire 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 React, { useCallback } from 'react'; | |
import { useFirestoreCollectionData, useFirestore } from 'reactfire'; | |
function useProjects() { | |
// lazy load the Firestore SDK | |
const firestore = useFirestore() | |
const projectsRef = firestore.collection('projects') | |
// subscribe to the do throws a Promise for Suspense to catch, | |
// and then streams live updates | |
const { data: projectsList } = useFirestoreCollectionData(projectsRef); | |
// Create handlers | |
async function addProject(newProjectData) { | |
await projectsRef.add(newProjectData) | |
} | |
const handlers = { | |
addProject: useCallback(addProject, [projectsRef]) | |
} | |
// return array of [data, handlers] to match hooks like useState | |
return [projectsList, handlers]; | |
} | |
export default function SomeComponent() { | |
const [projects, { addProject }] = useProjects() | |
return ( | |
<div> | |
<h2>Projects</h2> | |
<pre>{JSON.stringify(projects, null, 2)}</pre> | |
<button onClick={() => addProject({ name: 'some project' })}>Add Project</button> | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment