AllowedRoles in react lead to unothorized page, though role is correct

13 Views Asked by At

The target is to implement protected routes using RTKQuery and React Router 6. The problem is that whenever i reload the page I get redirected to unouthorized component, not to the outlet

I am trying to make protected routes using allowed roles. To fetch data from server I Use RTKQuery

   export const userAPI = apiSlice.injectEndpoints({
      endpoints: (build) => ({
    getUser:build.query<IPersonInitial, void | null>({
      query: () => {
        return ({
          url: `${Endpoints.User.PROFILE}`,
      })},
      async onQueryStarted(args, { dispatch, queryFulfilled }) {
        try {
          const { data } = await queryFulfilled;
          dispatch(setUser(data));
        } catch (error) {
          console.log(error)
        }
      },
      providesTags: ['User'],      
    }),
  })
});

To check if user is authorized added a custom hook


export const useAuthCheck = () => {
  const dispatch = useAppDispatch();
  const location = useLocation();
  const from = location.state?.from?.pathname || '/';
  const isUserSuccess = useAppSelector(selectIsUserSuccess);
  const isUserError = useAppSelector(selectIsUserError);
  const token = localStorage.getItem(StorageName.token);
  const isPreload = useAppSelector((state) => state.user.isPreloaded);
  const user = userAPI.endpoints.getUser.useQueryState().data;

  console.log({isPreload})
  useLayoutEffect(() => {
    if (token && !Boolean(user)) {
      dispatch(userAPI.endpoints.getUser.initiate());    
    }
  },[])
 
  useEffect(() => {
    if (Boolean(user)) {
      dispatch(setPreloaded(false)); 
    } 
    
    if (!token) {
      dispatch(setPreloaded(false));
    }

    if (isUserError) {
      dispatch(setPreloaded(false)); 
    }   

  }, [isUserSuccess, isUserError, dispatch, token]);

  return { from, isPreload, user };
};

and get the data in component Require Auth

export const RequireAuth = ({ allowedRoles }: IRequireAuth) => {
  const { isPreload, user, location } = useAuthCheck();

  return  isPreload 
  ? (<Loader />)
  : (
    allowedRoles.includes(user?.role!) 
      ? <Outlet />
      : Boolean(user)
        ? <Navigate 
            to='/unauthorized' 
            state={{ from: location}} 
            replace 
          />
        : <Navigate 
            to='/login' 
            state={{ from: location}}
            replace 
          />
  );
};

But every time i get redirected to unauthorized component, although the role is correct

0

There are 0 best solutions below