Navigating to a page without using hook useRouter
Unanswered
Thrianta posted this in #help-forum
ThriantaOP
hello! there was a need inside the function to transfer the user to the application page (let's say / test). there is no access to the useRouter() hook inside the function and there is no way to throw it from the outside. question: can I use location.href/replace, or does next have built-in functions for similar cases?
9 Replies
you can use "redirect"
import { redirect } from 'next/navigation'
redirect('/auth/login')@Roberto Duran you can use "redirect"
ThriantaOP
I'm testing now and I getting this error: Error: NEXT_REDIRECT
with this code:
import { redirect } from "next/navigation";
export const logoutUser = async () => {
await $axios.post("/logout");
redirect("/login");
};
there is no redirect. why?
with this code:
import { redirect } from "next/navigation";
export const logoutUser = async () => {
await $axios.post("/logout");
redirect("/login");
};
there is no redirect. why?
it throws error to work
you just need to not catch it, or rethrow the error
@riský it throws error to work
ThriantaOP
I don't understand you a bit. I have just read about the error next_redirect in the next dock, but if I get an error, then how will redirect happen?
if this is a client component is recommended to use the use useRouter
for example
import { useRouter } from 'next/navigation'
const router = useRouter()
export const logoutUser = async () => {
await $axios.post("/logout");
router.push("/login")
};
for example
import { useRouter } from 'next/navigation'
const router = useRouter()
export const logoutUser = async () => {
await $axios.post("/logout");
router.push("/login")
};
bcs the try catch could brake the redirect fucntion
another solution could be use the redirect("/login"); inside of your api call
another solution could be use the redirect("/login"); inside of your api call
and for a full explanation of the redirect here is vercel docs
https://nextjs.org/docs/app/api-reference/functions/redirect
https://nextjs.org/docs/app/api-reference/functions/redirect