Skip to content

Instantly share code, notes, and snippets.

@MorenoMdz
Created March 16, 2021 22:41
Show Gist options
  • Save MorenoMdz/241164562ee7894d609ec32356c1b472 to your computer and use it in GitHub Desktop.
Save MorenoMdz/241164562ee7894d609ec32356c1b472 to your computer and use it in GitHub Desktop.
Firebase ReactFire react hook example
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