Skip to content

Instantly share code, notes, and snippets.

@prescottprue
Last active February 11, 2021 03:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prescottprue/108ce7b7827e2305b05cffad4cf9ca55 to your computer and use it in GitHub Desktop.
Save prescottprue/108ce7b7827e2305b05cffad4cf9ca55 to your computer and use it in GitHub Desktop.
Custom hook which makes use of reactfire hooks
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