I am using firebase as backend for in my Next.js project. While using Routing I get some errors:
My Code:
"use client";
import { useAuthContext } from "@/context/AuthContext";
import Login from "./login/Loginpage";
import { useRouter } from "next/navigation";
import React from "react";
export default function Home() {
const { user } = useAuthContext();
const router = useRouter();
const data = user == null ? <Login /> : router.push("../admin");
return <>{data}</>;
}
Everything works well but I get following errors in console.
Warning: Cannot update a component (`Router`) while rendering a different component (`Home`). To locate the bad setState() call inside `Home`, follow the stack trace as described in https://reactjs.org/link/setstate-in-render
at Home (webpack-internal:///(app-client)/./src/app/adminLogin/page.js:20:91)
at InnerLayoutRouter (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/layout-router.js:227:11)
at RedirectErrorBoundary (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/redirect-boundary.js:73:9)
at RedirectBoundary (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/redirect-boundary.js:81:11)
at NotFoundBoundary (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/not-found-boundary.js:59:11)
I tried a lot to fix it Below code does not give any error but the DOM is loaded before routing
'use client'
import React from "react";
import { useAuthContext } from "@/context/AuthContext";
import { useRouter } from "next/navigation";
import Login from "./login/Loginpage";
function Page() {
const { user } = useAuthContext()
const router = useRouter()
React.useEffect(() => {
if (user == null) router.push("../admin")
}, [user])
return (<><Login/></>);
}
export default Page;
Is there any way to route before the DOM is loaded OR Is there any way to resolve the error in first code?
You can use redirect instead:
import { redirect } from 'next/navigation'
const data = user == null ? <Login /> : redirect ("../admin");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With