React-Redux State Management – Created a hook to verify user’s role, but not working properly

I have created a hook called useAuth.ts:

const useAuth = (requiredRole: string) => {
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  const { currentUser, status } = useAppSelector((state) => state.user);
  const loading = useAppSelector((state) => state.loading.loading);

  useEffect(() => {
    if (status === 'idle') {
      console.log('Dispatching loadUser');
      dispatch(loadUser());
    }
  }, [status, dispatch]);

  useEffect(() => {
    console.log('Auth Check: Current User:', currentUser);
    console.log('Auth Check: Required Role:', requiredRole);
    console.log('Auth Check: Status:', status);
    console.log('Auth Check: Loading:', loading);

    if (!loading && status === 'succeeded') {
      if (!currentUser) {
        console.log('No current user, redirecting to login');
        navigate('/login');
      } else if (currentUser.role !== requiredRole) {
        console.log('User role does not match required role, redirecting to home');
        navigate('/');
      }
    }
  }, [currentUser, status, loading, navigate, requiredRole]);
};

export default useAuth;

This hook is used to check for a single page I have called adminPanel.

Currently, when I try to access the page while logged in as a admin user, it redirects me to the /login page anyways.

Here is our sessionLoader.tsx:

const SessionLoader: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const dispatch = useDispatch<AppDispatch>();
  const { currentUser, status } = useSelector((state: RootState) => state.user);
  const loading = useSelector((state: RootState) => state.loading.loading);

  useEffect(() => {
    const token = localStorage.getItem('sessionToken');
    if (token && status === 'idle') {
      console.log('Token Found:', token);
      dispatch(loadUser());
    }
  }, [dispatch, status]);

  useEffect(() => {
    console.log('SessionLoader: CurrentUser:', currentUser);
    console.log('SessionLoader: Status:', status);
    console.log('SessionLoader: Loading:', loading);
  }, [currentUser, status, loading]);

  if (status === 'loading' || loading) {
    return (
      <Box
        sx={{
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          height: '100vh',
        }}
      >
        <CircularProgress />
      </Box>
    );
  }

  return <>{children}</>;
};

export default SessionLoader;

We have a userSlice.ts, that handles the loadUser action:

export const loadUser = createAsyncThunk(
  'users/loadUser',
  async (_, { rejectWithValue, dispatch }) => {
    dispatch(setLoading(true));
    const token = localStorage.getItem('sessionToken');
    if (!token) {
      dispatch(setLoading(false));
      return rejectWithValue('No session token found');
    }
    try {
      const userResponse = await axiosInstance.get('/api/users/verify/me', {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      const user = userResponse.data.user;
      dispatch(setLoading(false));
      return user;
    } catch (err) {
      let errorMessage = 'An unknown error occurred';
      if (axios.isAxiosError(err) && err.response) {
        errorMessage = err.response.data?.message || err.message;
      } else if (err instanceof Error) {
        errorMessage = err.message;
      }
      dispatch(setLoading(false));
      return rejectWithValue(errorMessage);
    }
  }
);

For the life of me, I cant get it to display the page correctly. It seems like the page is redirecting before it can verify the user. Here is our chrome console logs when trying to access the restricted page:

If you need any more specific code, ask away. Ive spent two days trying to figure this out so i’m open to any and all help! Thanks in advance 🙂

I am expecting the currentUser details to load, be verified, and load the admin page. But instead, its kicking me back to the /login page as if we are not logged into an admin account. I can see in the network tab in chrome devtools that the actual content of the admin page is loaded.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật