How do I persist a user across my app? Every time I create a user via my sign up page, if I reload the page – the user is no longer logged in. I have looked into persistence on the official documentation but am still not sure when to use persistence functions VS. the onAuthStateChange function.
This signup page is just a simple email, password, confirm password form. I omitted the render because that’s not relevant. Once the user submits their data, they are redirected via react-router-dom to a dashboard page. And once again, the user data renders once, but on page reload disappears.
Signup component:
import React, {useRef, useState, useEffect} from 'react'
import {Link, Navigate, useNavigate} from 'react-router-dom'
import { useAuth } from '../contexts/AuthContext'
import { auth } from '../firebase'
export default function
Signup() {
//Email Input
const emailRef = useRef()
const [email, setEmail] = useState("")
const [emailFlag, setEmailFlag] = useState()
//Password Input
const passwordRef = useRef()
const [password, setPassword] = useState("")
const [passwordFlag, setPasswordFlag] = useState()
//Password Confirmation Input
const passwordConfirmRef = useRef()
const [passwordConfirm, setPasswordConfirm] = useState("")
const [passwordMatchFlag, setPasswordMatchFlag] = useState()
//Destructure Authorization Functionality
const { currentUser, signup } = useAuth()
const navigate = useNavigate()
useEffect(() => {
verify()
},[password, passwordConfirm])
//Verify fields are passing
const verify = () => {
//set default flag values
setPasswordFlag(true)
setPasswordMatchFlag(true)
//Verify length
if(passwordRef.current.value.length >= 6) {
setPasswordFlag(false)
}
//Verify match
if(passwordRef.current.value === passwordConfirmRef.current.value) {
setPasswordMatchFlag(false)
}
}
const handleSubmit = async () => {
//if values pass
if(passwordFlag === false && passwordMatchFlag === false){
await signup(auth, email,password)
.then(console.log('successfuly signed up'))
.then(console.log(currentUser))
.then(navigate('/dashboard'))
}
}
The following is Auth Provider setup.
import React, {useContext, useState, useEffect, createContext} from 'react'
import {auth} from '../firebase'
import { createUserWithEmailAndPassword, onAuthStateChanged } from 'firebase/auth'
const AuthContext = createContext()
export function useAuth() {
return useContext(AuthContext)
}
export function AuthProvider({children}) {
const [currentUser, setCurrentUser] = useState()
function signup(auth, email, password){
createUserWithEmailAndPassword(auth, email, password)
}
onAuthStateChanged(auth, (user) => {
setCurrentUser(user)
})
const value= {
currentUser,
signup
}
return (
<AuthContext.Provider value={value}>
{children}
</AuthContext.Provider>
)
}