I created a route in my Next.JS app on Firebase and though I intended to be very careful, I get a problem.
First of all here is the code (page.tsx) for the route:
'use client';
import React, {useState,useEffect} from "react";
import firebase from "../../firebase/initFirebase";
import DrillManage from '../components/drillMng'
export default async function MemberPage() {
const [memberID, setMemberID] = useState("");
const [userID, setUserID] = useState("");
if (typeof window !== "undefined") {
const memberID = window.location.pathname.substring(1)
setMemberID(memberID)
} else console.log('window.location is UNDEFINED')
useEffect(() => {
let dbRef = firebase.database().ref('Members')
dbRef.child(memberID)
.once('value', (snapshot) => {
const usrID = JSON.parse(JSON.stringify(snapshot.child('UserID')))
setUserID(usrID)
})
}, [memberID]);
return (
<DrillManage usrID={userID} />
)
}
And this is what I see in my web browser:
Unhandled Runtime Error
Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
Call Stack
I don't see in my code anything which could give raise to some infinite loop.
But I may be wrong. Can anyone spot something I am doing the wrong way? And let me know?
I have also tried the following code, but for some reason that I do not catch userID is never set.
'use client';
import React, {useState,useEffect} from "react";
import firebase from "../../firebase/initFirebase";
import DrillManage from '../components/drillMng'
import { useRouter, usePathname, useSearchParams } from 'next/navigation'
export default async function MemberPage() {
const [userID, setUserID] = useState("");
const pathname = usePathname().substring(1)
const [memberID, setMemberID] = useState(pathname);
console.log('pathname=',pathname)
console.log('memberID=',memberID)
useEffect(() => {
let dbRef = firebase.database().ref('Members')
dbRef.child(memberID)
.once('value', (snapshot) => {
const usrID = JSON.parse(JSON.stringify(snapshot.child('UserID')))
console.log('usrID=',usrID)
setUserID(usrID)
})
}, [pathname,memberID]);
return (
<DrillManage usrID={userID} />
)
}