Created
March 16, 2021 22:41
-
-
Save MorenoMdz/241164562ee7894d609ec32356c1b472 to your computer and use it in GitHub Desktop.
Firebase ReactFire react hook example
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 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
https://prescottprue.medium.com/react-and-firebase-without-redux-5c1b2b6a6ba1