Next.js Discord

Discord Forum

redirect function fail when refresh page

Answered
Common carp posted this in #help-forum
Open in Discord
Common carpOP
Hi, I'm facing a problem with redirect function from next/navigation. When the profile object is null and I try to access the route /my-profle, an error occurs "react-dom.development.js:11003 Uncaught Error: Rendered more hooks than during the previous render".
It worked fine when soft navigation. The error only occurs when I try hard navigation. Can anyone help me ?
/my-profle
const page = () => {

  const { profile } = useAppSelector((state) => state.authReducer);

  if (!profile?.accessToken) {
    return redirect("/");
  }

  return (
    <p className="mt-[10px]">
        hello
    </p>
  );
};
Answered by Ray
use router.push() instead in client component
const router = useRouter()

useEffect(() => {
  if (!profile?.accessToken) {
    router.push("/")
  }
}, [profile])
View full answer

15 Replies

Answer
Common carpOP
I have tried that way but I dont want the content rendered before I make sure the user logged in
Common carpOP
I have another component uses redirect function same as the code above but the error did not occur when I accessed the route without logging in
@Ray define a loading state
Common carpOP
Can you give me an example ?
@Common carp I have another component uses redirect function same as the code above but the error did not occur when I accessed the route without logging in
redirect throw and NEXT_REDIRECT error and next will redirect when it is able to catch the error
@Common carp Can you give me an example ?
define it in your redux store
const router = useRouter()
const { isLoading, profile } = useAppSelector((state) => state.authReducer);

useEffect(() => {
  if (!profile?.accessToken) {
    router.push("/")
  }
}, [profile])

if (isLoading) return <div>loading...</div>

...
Common carpOP
How can I define it true or false? For example, When I not log in and I try to access '/my-profile' then it still render the content below right?
true before you load the profile data
false after you load the profile data
Common carpOP
I mean the profile data is only loaded when I try to login. But the case I mention is I do not login and try to access the route by modifying the url. Sorry, If I misunderstand your way
then just return null if profile is not there
@Ray then just return null if profile is not there
Common carpOP
Thanks. It worked
@Ray redirect throw and NEXT_REDIRECT error and next will redirect when it is able to catch the error
Common carpOP
But can you explain more detail?