The title summarize it. The code below works when trying to navigate from the UI, but when I manually enter the path, it doesn't redirect to the Login page. What I'm not seeing?
import { useNavigate } from "react-router-dom";
const DetailView = () => {
const navigate = useNavigate();
let token = localStorage.getItem('token');
return (
<>
{!token && navigate("/", { replace: true })}
<h2>DetailView</h2>
</>
);
};
export default DetailView;
CodePudding user response:
you need to perform this operation in useEffect
useEffect(() => {
!token && navigate("/", { replace: true });
}, []);
CodePudding user response:
You should do it in a useEffect, and include the token as a dependency.
useEffect(() => {
!token && navigate("/", { replace: true });
}, [token]);
CodePudding user response:
following the answers by Aman Sadhwani and Moath: what happen is :
in your code (not sure about this one) the navigation will happen only using the ui, because that what registers it, manually adding the url will not trigger the token to navigate
but when using built in useEffect
you tell react to constantly update,
it has componentDidMount
, componentDidUpdate
, and componentWillUnmount
blended in
useEffect(() => {
!token && navigate("/", { replace: true });
}, [token]);
that will trigger the navigation each time the token changes, and always use [] in the end to avoid being in an infinite loop either empty or with passed data
read more react-hooks-effect