Home > OS >  ReactJS: How to redirect user based on usertype
ReactJS: How to redirect user based on usertype

Time:01-30

I have three types of user 'A', 'B', 'C' in my react project. These values are stored in local storage. When a user login successfully, I wanted to redirect them to their specific route '/a','/b','/c'..

Here is what I tried so far, but it does not work properly

const submit = async (e) => {
    e.preventDefault();
    if (password.length < 2) return;
    if (email.length < 2) return;

    try {
      const response = await apiClient.auth.login({
        username: email,
        password,
      });
      props.set_token(response.data.token);
      props.set_user_data(response.data.user);
      props.set_user_status({
        approved: response.data.user.approved,
        loggedIn: true,
        token: response.data.token,
      });
      if (response.status === 200) { //ON LOGIN SUCCESSFULL
        if (type.user.user_type === "A") {
          <Redirect to="/A" />;
        } else if (type.user.user_type === "B") {
          <Redirect to="/B" />;
        } else if (type.user.user_type === "C"){
          <Redirect to="/C" />;
        }
        else{
          <Redirect to="/signin" />;
        }
      }
    } catch (err) {
      console.log(err);
    }
  };

Any help? Thanks

CodePudding user response:

What you need is React Router to accomplish this... Resource to help you React Router

Try replacing your conditional block with this instead

if (response.status === 200) { //ON LOGIN SUCCESSFULL
    if (type.user.user_type) {
      <Redirect to={`/${type.user.user_type}`}/>;
    }  else {
      <Redirect to="/signin" />;
    }

CodePudding user response:

If you are using React Router v6, you need to use the useNavigate hook:

const navigate = useNavigate();

And then:

if (type.user.user_type === "A") {
  navigate('/A');
} else if (type.user.user_type === "B") {
  navigate('/B');
} else if (type.user.user_type === "C"){
 navigate('/C');
}
  •  Tags:  
  • Related