Coming soon - Get a detailed view of why an account is flagged as spam!
view details

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.

0
Protected routes in react router v6.10
Post Flair (click to view more posts with a particular flair)
Post Body

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.

Author
Account Strength
80%
Account Age
11 years
Verified Email
Yes
Verified Flair
No
Total Karma
97
Link Karma
51
Comment Karma
46
Profile updated: 3 days ago
Posts updated: 1 year ago

Subreddit

Post Details

We try to extract some basic information from the post title. This is not always successful or accurate, please use your best judgement and compare these values to the post title and body for confirmation.
Posted
1 year ago