0
votes

i am developping a Reactjs-nodejs application. I would like to make a JWT authentification. when we log in, i give a unique token to the user. Then, thanks to this token, if it is valid, i allow the user to navigate through my router. my private route component is like : PrivateRoute

My function getId is like that:

async function getId(){ let res = await axios('_/api/users/me',{config}).catch(err => { console.log(err)});

return res+1; }

Finally the config component is the token stored in the localStorage :

const config = { headers: { Authorization: ${window.localStorage.getItem("token")} } };

GetId() returns the id of the user if logged in, else it is null.

The problem now is that my privateRoute always redirect to "/" path. I think it is because of the axios(promise) that gives me the userId too late. please tell me if you understand well and if you have a solution. Thanks you

2
Welcome to stackoverflow:) Please move the relevant code from the linked image to your question.Simon Thiel

2 Answers

0
votes

You can create private-route like this .

const PrivateRoute = ({ component: Component, ...props }) => {
  return (
    <Route
      {...props}
      render={innerProps =>
        localStorage.getItem("Token") ? (
          <Component {...innerProps} />
        ) : (
          <Redirect
            to={{
              pathname: "/",
              state: { from: props.location }
            }}
          />
        )
      }
    />
  );
};

then you can use

<PrivateRoute path="/" component={FIlname} />
0
votes

if you are using redux, you can make the following:

in reduer:

case LOGIN_ADMIN_SUCCESS:
            localStorage.setItem("token", action.payload.token);
            return {
                ...state,
                user: action.payload,
                isSignedIn: true,
                loadingSignIn: false,
                token: action.payload.token,
            };

then in your private router you have to check these values, like

const PrivateRoute = ({ component: Component, admin, ...rest }) => (
    <Route
        {...rest}
        render={(props) => {
            if (admin.loadingSignIn) {
                return <h3>Loading...</h3>;
            } else if (!admin.isSignedIn) {
                return <Redirect to="/login" />;
            } else {
                return <Component {...props} />;
            }
        }}
    />
);