reactjsreact-router-domtoast

show a toast for private route when user not logged in


I'm trying to show a toast to alert users who haven't logged in but tried to change the URL to get to other pages.

I'm using toast from sonner.

import { useEffect } from 'react'
import { Outlet, useNavigate } from 'react-router-dom'
import Cookies from 'universal-cookie'
import { toast } from 'sonner'

const PrivateRoute = () => {
  const cookie = new Cookies(null, { path: '/' })
  const navigate = useNavigate()

  useEffect(() => {
    if (!cookie.get('token')) {
      toast.error('You are not authorized to access this page')
      navigate('/login', { replace: true, })
    }
  }, [navigate])

  return <Outlet />
}

export default PrivateRoute

Solution

  • The PrivateRoute component only checks the stored cookie once when the component mounts. I suspect you meant for this check to happen after any navigation action, i.e. when the app URL path changes. For this you can use the useLocation hook and add the location or location.pathname as dependency.

    Example:

    import { useEffect } from 'react';
    import { Outlet, useLocation, useNavigate } from 'react-router-dom';
    import Cookies from 'universal-cookie';
    import { toast } from 'sonner';
    
    const PrivateRoute = () => {
      const { pathname } = useLocation();
      const navigate = useNavigate();
    
      useEffect(() => {
        const cookie = new Cookies(null, { path: '/' });
    
        if (!cookie.get('token')) {
          toast.error('You are not authorized to access this page');
          navigate('/login', { replace: true });
        }
      }, [pathname, navigate]);
    
      return <Outlet />;
    };