Home > Mobile >  Navigate in react router 6 doesn't redirect to another page
Navigate in react router 6 doesn't redirect to another page

Time:12-18

I have a component with logout button. When I click on it, function logout works but doesn't redirect me to login page. Could you explaine me why it happens?

const Header = () => {

const token = localStorage.getItem('token');
const userName = useSelector(getUserSelector);
const logout = async () => {
    const res = await axios.delete(url, {
        headers: {
            Authorization: token,
        },
    });
    if (res.status === 200) {
        localStorage.removeItem('token');

        <Navigate to='/login' />;
    } else {
        console.log(res);
    }

};

return (
    <header className='header'>
        <Logo className='header__logo' />
        {token && (
            <div className='header__description'>
                <div className='header__user'>{userName || 'Admin'}</div>
                <Button
                    className='header__button'
                    buttonName={LOGOUT_BUTTON}
                    onClick={logout}
                />
            </div>
        )}
    </header>
);

};

CodePudding user response:

You can't return JSX from a callback and expect it to be rendered like this. Use the useNavigate hook and do an imperative navigation. If you want to redirect then also specify the replace option.

const Header = () => {
  const navigate = useNavigate();

  const token = localStorage.getItem('token');
  const userName = useSelector(getUserSelector);

  const logout = async () => {
    const res = await axios.delete(url, {
      headers: {
        Authorization: token,
      },
    });
    if (res.status === 200) {
      localStorage.removeItem('token');

      navigate("/login", { replace: true });
    } else {
      console.log(res);
    }
  };

  return (
    ...
  );
};

CodePudding user response:

That's the Navigate component. if you want to programmatically navigate there is a hook for that:

const token = localStorage.getItem("token");
const userName = useSelector(getUserSelector);
const navigate = useNavigate();

const logout = async () => {
  const res = await axios.delete(url, {
    headers: {
      Authorization: token,
    },
  });
  if (res.status === 200) {
    localStorage.removeItem("token");
    navigate("/login");
  } else {
    console.log(res);
  }
};
  • Related