Below is the simplified code snippet I am currently using:
import { useState, useEffect, useContext } from 'react'
import { useRouter } from 'next/router'
import { firestore } from './firebase-config'
import { getDoc, doc } from 'firebase/firestore'
export default function HomePage() {
const router = useRouter()
const user = useContext(AuthContext) // contains user object -> user.user
const [loading, setLoading] = useState(true)
useEffect(() => {
const fetchData = async() => {
setLoading(true)
const uid = user.user.uid // uid of user in firebase auth
const id = router.query.id // id param of url
const docRef = doc(firestore, `...`)
// doc in a collection that references the above uid and id
const docSnap = await getDoc(docRef)
// get the document from firestore
if (docSnap.exists()) {
importData(docSnap.data()) // add data to store to re-render page
setLoading(false)
} else {
router.push('/main')
// redirects user to '/main' if they are not logged in; otherwise return to '/'
}
}
fetchData()
}, [router.query, user.user])
return (
<>
{/* */}
</>
)
}
The main objective here is to load the document linked with the user's uid
and the id
parameter of the current webpage like /main/[id]
.
The fetched Firestore document is then added to the store triggering the rebuild of the HomePage function to display the information.
uid
can be accessed through user.user.uid
, which gets set using onAuthStateChanged
in app.js
id
can be retrieved via router.query.id
, which is established using useRouter()
at the top level
The mentioned useEffect()
does its job but momentarily, as soon as the data loads and the component refreshes, it gets directed to '/main'
. This occurs because initially both uid
and id
begin as undefined
. As a result, on the first run of the useEffect
hook, the else
condition executes and subsequently runs again after retrieving the user
and router
objects to fetch the data. However, by then, the webpage transitions to './main'
.
I would greatly appreciate any assistance in resolving this issue.
Additionally, if the document doesn't exist but the user is logged in, they should be taken back to './main'
; if they are not logged in, they should be redirected to the root ('./'
)
Thank you in advance for your help!