Home > database >  i want to redirect user after login based on their role and stop them to access this page in React.j
i want to redirect user after login based on their role and stop them to access this page in React.j

Time:02-24

I had did this using Redux library and MongoDB and its works fine with this but now i am doing same thing with mysql so its not working well. This logic always redirect all users to admin dashboard. i want do like, if i do isAdmin="true" it will redirect to admin dashboard and stop to going coordinator dashboard. and if isCoordinator="true" then redirect to coordinator dashboard and not able to access admin dashboard. how can i that?

*This is my Admin.js file. where i did logic to private access path.

import { useSelector } from "react-redux";
import { Route, Routes, Link, useNavigate } from "react-router-dom";
import UsersList from "./UsersList";
import UsersEntry from "./UsersEntry";
import Projects from "./projects/Projects";
import "./Admin.css"

export default function Admin() {
    let navigate = useNavigate();
const userState = useSelector(state=> state.loginUserReducer)
const {currentUser} =userState;
 useEffect(() => {
  // This code check Role of user who logged in and if not coordinator then restrict(stop) to going on this private page. By getItem and check === !currentUser.isCoordinator.
    if(localStorage.getItem('currentUser') === null || !currentUser.isAdmin){
       navigate('/coordinators');
       if(localStorage.getItem('currentUser') === null || !currentUser.isCoordinator){
        navigate('/');
     }
    }   
 }, []) 

*This is UserAction.js fie.


export const loginUser = (user) => async (dispatch) => {
    dispatch({type: "USER_LOGIN_REQUEST"});
    try {
        const response = await axios.post("http://localhost:4000/login",user);
        console.log(response.data);
        dispatch({type:"USER_LOGIN_SUCCESS", payload: response.data});
        localStorage.setItem('currentUser',JSON.stringify(response.data));           
        window.location.href = "/admin"; 
        
    } catch (error) {
        dispatch({type: "USER_LOGIN_FAIL", payload: error})
    }
    }

*This is UserReducer.js.

switch (action.type){
  case "USER_LOGIN_REQUEST":
      return{
          loading:true,
      };
  case "USER_LOGIN_SUCCESS":
      return{
          success: true,
          loading: false,
          currentusers: action.payload,
      };
  case "USER_LOGIN_FAIL":
      return{
          error: action.payload,
          loading:false,
      };
  default:
      return state; 
 }
};

*This is Store.js.

import thunk from 'redux-thunk';
import {composeWithDevTools} from 'redux-devtools-extension';
import {loginUserReducer} from './UserReducer';

const currentUser = localStorage.getItem('currentUser') ? JSON.parse(localStorage.getItem('currentUser')) : null 

const rootReducer = combineReducers({loginUserReducer :  loginUserReducer});

const initialState = {
    loginUserReducer: {
        currentUser : currentUser
    }
} 
const middleware = [thunk]

const store = createStore(
    rootReducer,
    initialState,
    composeWithDevTools(applyMiddleware(...middleware))
    );

    export default store;

CodePudding user response:

In your useEffect inside the dependency array pass the currentUser so whenever it is changed useEffect will be triggered. In current scenario when the array is empty it just happens on the page load the very first time.

Here is the possible thing to try:

 useEffect(() => {
  // This code check Role of user who logged in and if not coordinator then restrict(stop) to going on this private page. By getItem and check === !currentUser.isCoordinator.
    if(localStorage.getItem('currentUser') === null || !currentUser.isAdmin){
       navigate('/coordinators');
       if(localStorage.getItem('currentUser') === null || !currentUser.isCoordinator){
        navigate('/');
     }
    }   
 }, [currentUser]) <================

Secondly also check your nested if condition. You can use an else if as well so incase its not admin it will go inside if and if it is admin then it can go inside the else if block. But that is totally up to you, just a suggestion.

  • Related