This post has been de-listed
It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.
Hello, in a team we've started a project using react, firebase and react-router v6.10 with the new object router. Does anyone have any example on how to use the firebase auth and react-router with the loader functions in order to have the user loaded before the page is rendered. Some sort of protected route examples. I know how to do it on older react-router versions, but with this one I just can't.
We have the standard
const { user } = useFirebaseContext()
But when the page is reloaded, it returns a null first and therefore an error.
This is the code I'm working withThis is the function used to sign in:
export async function signInWithEmail (user) {
try {
const { email, password } = user
await setPersistence(firebaseAuth, browserSessionPersistence)
const userSignIn = await signInWithEmailAndPassword(firebaseAuth, email, password)
const { uid } = userSignIn.user
const docSnapshot = await getDoc(doc(db, 'users', uid))
console.log(docSnapshot.data())
const userData = docSnapshot.data()
return userData
} catch (error) {
const errorCode = error.code
throw new Error(ERRORS_LOGGING_USER[errorCode])
}
}
This is the context
useEffect(() => {
const unSubscribe = onAuthStateChanged(firebaseAuth, async currentUser => {
setLoading(true)
if (currentUser) {
const userInfo = await getCurrentUserInfo()
setUser(userInfo)
} else {
setUser(null)
}
setLoading(false)
})
return () => unSubscribe()
}, [])
const logout = () => signOut(firebaseAuth)
return (
<FirebaseContext.Provider value={{ login, user, logout, loading }}>
{children}
</FirebaseContext.Provider>
)
}
And the error provided is "Cannot destructure property 'uid' of 'firebaseAuth.currentUser' as it is null."
I dont understand how is it that it cant get the user from the memory on the first render.
Post Details
- Posted
- 1 year ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/reactjs/com...