skip to Main Content

In my app currently on React-Router v5, we have a redirect link from an email that includes a "referrer=email" param that we use to determine some initial state on the login/signup pages:

const queryParameters = new URLSearchParams(search);
const referrer = queryParameters.get('referrer');
const [open, setOpen] = useState(
  pathname === '/signup' && referrer !== 'email' ? false : true
);

However after we have made that determination, we want to strip the "referrer" param from the URL search string which we are currently doing with history.replace. However, the docs for the migration to v6 and useNavigate do not seem to factor in this use case of the replace functionality:

useEffect(() => {
  // remove params from URL
  history.replace({
    referrer: '',
  });
}, []);

Is there an option with the new navigate API that would map to this?

2

Answers


  1. Have you tried

    
    const navigate = useNavigate();
    //snip...
    
    useEffect(() => {
      const url = ...;
      navigate(url);
    
    }[])
    
    

    source

    Login or Signup to reply.
  2. See options.replace for the details how to issue a RELACE action instead of a PUSH action, similar to history.replace.

    If you just want to update the URL search params then use the useSearchParams hook. It works just like the useNavigate hook but works on the queryString, e.g. the search params.

    Example:

    import { useMatch, useSearchParams } from 'react-router-dom';
    
    ...
    
    const isSignup = useMatch("/signup");
    const [searchParams, setSearchParams] = useSearchParams();
    
    const [open, setOpen] = useState(() => {
      const referrer = searchParams.get("referrer");
      return isSignup && referrer === 'email';
    });
    
    useEffect(() => {
      setSearchParams(searchParams => {
        // remove the "referrer" from the queryString
        searchParams.delete("referrer");
    
        // return the next queryString
        return searchParams;
      }, { replace: true }); // <-- redirect action
    }, []);
    

    Example using useNavigate if this is the hook you really want to use:

    import { useNavigate, useLocation } from 'react-router-dom';
    
    ...
    
    const navigate = useNavigate();
    const { pathname, search } = useLocation();
    const searchParams = React.useMemo(() => new URLSearchParams(search), [search]);
    
    const [open, setOpen] = useState(() => {
      const referrer = searchParams.get("referrer");
      return pathname === '/signup' && referrer === 'email';
    });
    
    useEffect(() => {
      // remove the "referrer" from the queryString
      searchParams.delete("referrer");
    
      // redirect to the current path with the update queryString
      navigate({
        pathname: ".",
        search: searchString.toString(),
      }, { replace: true });
    }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search