Home > Back-end >  React-router-dom Navigate not rendering page
React-router-dom Navigate not rendering page

Time:12-12

I'm trying to use a function to verify the user access Token that is stored on the local Storage, if the token is not valid, I want to redirect the user to /login page, but it is not working. It works if I use useNavigate. Below is my code.

axios.get(`${REACT_APP_EXPRESS_BACKEND_URL}/authroute/verifyjwt`, {
          headers: {
            Authorization: `Bearer ${auth?.accessToken}`,
          },
          withCredentials: true,
        })
        .then((res) => {
          if (res?.data?._id) {
            dispatch(
              userLoggedIn({
                accessToken: auth.accessToken,
                profile: auth.profile,
                user: auth.user,
                timestamp: auth?.timestamp,
              })
            );
             return children;
            }
          else {
            dispatch(userLoggedOut());
            localStorage.removeItem("accessToken");
            return <Navigate to="/login" state={{ from: location }} replace />;
          }
        })

CodePudding user response:

  1. import {useNavigate} from 'react-router-dom';

// make a variable using the useNavigate function

const navigate = useNavigate();

//Then change this line

return <Navigate to="/login" state={{ from: location }} replace />;

// to this

return navigate("/login")

OR

  1. import { redirect } from "react-router-dom";

// Use this

return redirect("/login");

Hope this helps you :))

CodePudding user response:

<Navigate /> is a React component. It only works if rendered (i.e. it is directly returned by a React component).

Talking strictly about your code snippet I would say that the hook should not work either, as hooks must also be called inside a React (functional) component. I assume though that your code, for some reason, is actually inside a React component and you correctly call the hook on the component root. You probably do the same thing with useDispatch.

If you necessarily need to redirect in that specific place (and your code is NOT inside a React component) you have to use the history API imperatively by using something like history.push. If the code is indeed inside a React component then just use the useNavigate hook and everything should be ok.

As a side note, it works the same with Redux too. If you need for instance to access the store state outside a React component you will not be able to use useSelector as it is a hook and well, must be called inside a functional component. That's when you need to actually import your store and imperatively call store.getState().

I mention this as usually network request are handled outside React components and sometimes you might need to access store state.

Hope this helps :)

  • Related