Search code examples
reactjsreact-hooksreact-routerreact-router-dom

Navigate the user to another URL using useNavigate() of react-router-dom-v6


I am working on a React 18 application and I am trying to navigate the guest user to the shipping page (URL: localhost:3000/shipping) from the cart page by clicking the Proceed to Checkout button. On clicking the button, the user should be first re-directed to the sign in page where he should sign in (on the SigninScreen page) and then proceed to the shipping page.

The current url when clicking the Proceed to Checkout button is (URL: localhost:3000/signin?redirect=shipping)

On clicking the SignIn button on the SignInScreen page I do a redirect in the useEffect() hook:

import { useSearchParams, useNavigate } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';

const userSignin = useSelector((state) => state.userSignin);
const { userInfo, loading, error } = userSignin;

const [searchParams] = useSearchParams();
const redirectUrl = searchParams.get('redirect') || '/';

const navigate = useNavigate();

useEffect(() => {
  // If the user is logged in, the user should redirected to the shipping page.
  if (userInfo) {
    navigate(redirectUrl, {replace: true});
  }
}, [userInfo, redirectUrl, navigate]);

Even after using {replace: true} the user does not get navigated to localhost:3000/shipping, instead it gets redirected to localhost:3000/signin/shipping

Could someone please guide me on what am I doing wrong?

Tried: Even after using {replace: true} the user does not get navigated to localhost:3000/shipping, instead it gets redirected to localhost:3000/signin/shipping

Expectation: The user should navigate to localhost:3000/shipping from localhost:3000/signin?redirect=shipping on signing the user in on the sign in screen by clicking the Sign In button


Solution

  • URLs which do not start with a / are treated as relative links to the current route. You are navigating the user to shipping when it should be /shipping.

    Here’s one way to add the starting slash:

    const redirectUrl = '/' + (searchParams.get('redirect') || '');