'How to save user to firestore while signup
I'm trying to save the user to the users collection on firestore when user sign up using github. But unfortunately I was not able to do that. I'm using firebase v9
useSignUp hook code(this runs when user click on signup button)
import { GithubAuthProvider, signInWithPopup } from "firebase/auth"
import { useState } from "react"
import { auth } from "../firebase/config"
import { useAuthContext } from "./useAuthContext"
export const useSignup = () => {
const [error, setError] = useState(false)
const provider = new GithubAuthProvider()
const { dispatch } = useAuthContext()
const signup = () => {
setError(null)
signInWithPopup(auth, provider)
.then(async (result) => {
const user = result.user
dispatch({ type: "LOGIN", payload: user })
})
.catch((error) => {
const errorMessage = error.message
console.log(errorMessage)
})
}
return { error, signup }
}
AuthContext Code:
import { createContext, useReducer, useEffect } from "react"
import { auth } from "../firebase/config"
import { onAuthStateChanged } from "firebase/auth"
import { createUserProfileDocument } from "../firebase/createUserProfileDocument"
export const AuthContext = createContext()
export const authReducer = (state, action) => {
switch (action.type) {
case "LOGIN":
return { ...state, user: action.payload }
case "LOGOUT":
return { ...state, user: null }
case "AUTH_IS_READY":
return { user: action.payload, authIsReady: true }
default:
return state
}
}
export const AuthContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(authReducer, {
user: null,
authIsReady: false,
})
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (user) => {
dispatch({ type: "AUTH_IS_READY", payload: user })
})
return unsubscribe
}, [])
return (
<AuthContext.Provider value={{ ...state, dispatch }}>{children}</AuthContext.Provider>
)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
