I have an issue with redirect to another page. I can’t use useNavigate() inside the function. Because it’s not an component. redirect also not working. How can i redirect?
import { redirect, useNavigate } from "react-router-dom";
import { ILogin } from "../Pages/Login/ILogin";
import { decode } from "./encodeDecode";
export const parseToken = () => {
const nav = useNavigate();
try {
const token: ILogin = decode(localStorage.getItem("token"));
return token;
} catch (error) {
console.log(error);
alert("Invalid Credentials");
localStorage.clear();
redirect("/login");
nav("/login");
}
};
when call redirect it’s not working
when call nav it’s throw an error as
Line 6:15: React Hook "useNavigate" is called in function "parseToken" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use" react-hooks/rules-of-hooks
Search for the keywords to learn more about each error.
webpack compiled with 1 error and 1 warning
I need a solution for redirecting in function.
5
Answers
The redirect function is not part of the standard React Router API and seems to be a misunderstanding or a mix-up with the useNavigate hook or the Navigate component.
change component name from
parseToken
toParseToken
and use like
<ParseToken
/>The error you’re seeing regarding
useNavigate
is pretty self explanatory – you cannot call a hook in a function that’s neither a React function (starts with a capital latter) or a custom hook (starts withuse
). Check out Rules of Hooks page in the React docs.As for the
redirect
function, it should be used in aloader
. Make sure you’ve set up your router as a withcreateBrowserRouter
to be able to use data API’s.try to
return redirect("/login");
like THISor
return <Navigate to="/login"/>
You are mixing a bunch of concepts. The first is that
redirect()
anduseNavigate()
are two different things:redirect()
is just an utility that returns aResponse
to be used to redirect insideloader
s andaction
s.useNavigate()
is an hook that allows you to programmatically navigate from a component.Since
useNavigate()
is an hook, it follows the hooks rules, meaning that it cannot be called inside a function, but nothing stops you to pass thenav
function as a parameter ofparseToken()
: