remix-run / react-router

Declarative routing for React

Home Page:https://reactrouter.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Bug]: `setSearchParams` do not provide the latest queryString passed as argument to `navigate`

jean-leclerc opened this issue · comments

What version of React Router are you using?

6.22.3

Steps to Reproduce

import {
  createBrowserRouter,
  RouterProvider,
  useNavigate,
  useSearchParams,
} from 'react-router-dom';

import './index.css';
import { useCallback, useEffect, useState } from 'react';

let router = createBrowserRouter([
  {
    path: '/',
    loader: ({ request }: { request: Request }) => {
      const searchParams = new URL(request.url).searchParams;
      console.log(`LOADER - search: ${searchParams.toString()}`);
      return null;
    },
    Component() {
      const [searchParams] = useSearchParams();
      console.log(`Component - search: ${searchParams.toString()}`);

      const [display, setDisplay] = useState(false);

      const navigate = useNavigate();
      const showGenericComponent = useCallback(() => {
        setDisplay(true);
        navigate({ search: '?display=on&pageSize=10' });
      }, [navigate]);

      const hideGenericComponent = useCallback(() => {
        setDisplay(false);
        navigate({ search: '' });
      }, []);

      return (
        <>
          <button
            onClick={display ? hideGenericComponent : showGenericComponent}
          >
            Show GenericComponent
          </button>
          {display && <GenericComponent />}
        </>
      );
    },
  },
]);

const GenericComponent = () => {
  const [_, setSearchParams] = useSearchParams();

  useEffect(() => {
    setSearchParams((prevSearchParams) => {
      console.log(`EFFECT - search: ${prevSearchParams.toString()}`);

      const searchParams = new URLSearchParams(prevSearchParams);
      const pageSize = parseInt(searchParams.get('pageSize') ?? '');
      if (Number.isNaN(pageSize) || pageSize > 1000) {
        searchParams.set('pageSize', '50');
      }

      return searchParams;
    });
  }, [setSearchParams]);

  return <div>Generic Component</div>;
};

export default function App() {
  return <RouterProvider router={router} fallbackElement={<p>Loading...</p>} />;
}

if (import.meta.hot) {
  import.meta.hot.dispose(() => router.dispose());
}

Expected Behavior

When the showGenericComponent( ) method is called:

  1. It executes setDisplay(true) and navigate({ search: '?display=on&pageSize=10' }).
  2. This causes GenericComponent to be displayed and in turn the useEffect it contains to be executed.

I expect that the functional version of setSearchParams (used within the useEffect) to provide a searchParams containing ?display=on&pageSize=10, which was the argument passed to the navigate function.

A use case could be, for example, to read the pagination information from the URL and fix it if it has unexpected values or some keys are missing. (see a toy example in the code above)

Actual Behavior

The setSearchParams is providing an empty searchParams (the value of the queryString before calling navigate).

I have seen that you could get the actual value of the queryString in the loader, and could therefore add such logic in the loader or derive it from the loader. However, I would expect that the functional version of useSearchParams to provide the latest version of the queryString.

Hmm.. it looks like you're overcomplicating things. If you store state in search params, you don't need to store it in useState as well.

function About() {
  const [searchParams] = useSearchParams();
  // get display state from search params
  const display = searchParams.get('display') === 'on';
  const navigate = useNavigate();
  const showGenericComponent = useCallback(() => {
    navigate({ search: '?display=on' });
  }, [navigate]);

  const hideGenericComponent = useCallback(() => {
    navigate({ search: '' });
  }, []);

  return (
    <>
      <button onClick={display ? hideGenericComponent : showGenericComponent}>
        {display ? 'Hide' : 'Show'} GenericComponent
      </button>
      {display && <GenericComponent />}
    </>
  );
}
const GenericComponent = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  const location = useLocation();
  // get current pageSize
  function getPageSize(s: string) {
    let pageSize = parseInt(s);
    if (!pageSize || Number.isNaN(pageSize) || pageSize > 1000) {
      pageSize = 50;
    }
    return pageSize;
  }
  const pageSize = getPageSize(searchParams.get('pageSize') ?? '');
  let data = {
    location: `${location.pathname}${location.search}`,
    params: {
      display: searchParams.get('display'),
      pageSize,
    },
  };

  return (
    <div>
      <h3>Generic Component</h3>
      <pre>{JSON.stringify(data, null, 2)}</pre>
      <b>Links with new search params</b>
      <ul>
        <li>
          <Link to={getSearchParams(searchParams, { pageSize: 100 })}>
            ?pageSize=100
          </Link>
        </li>
        <li>
          <Link to={getSearchParams(searchParams, { pageSize: 500 })}>
            ?pageSize=500
          </Link>
        </li>
        <li>
          <Link to={getSearchParams(searchParams, { pageSize: 1500 })}>
            ?pageSize=1500
          </Link>
        </li>
      </ul>
      <b>
        Update via <code>setSearchParams</code>
      </b>
      <ul>
        <li>
          <button
            onClick={() => {
              // modify existing search params
              searchParams.set('pageSize', '250');
              // update route with modified search params (which triggers a navigation/re-render)
              setSearchParams(searchParams);
            }}
          >
            <code>searchParams.set('pageSize', '250')</code>
          </button>
        </li>
      </ul>
    </div>
  );
};

/**
 * function to return querystring
 * from existing search params with updated values
 */
function getSearchParams(
  searchParams: URLSearchParams,
  newValues: Record<string, unknown>
) {
  const newSearchParams = new URLSearchParams(searchParams);
  Object.entries(newValues).forEach(([key, value]) =>
    newSearchParams.set(key, String(value))
  );
  return newSearchParams.size ? `?${newSearchParams}` : '';
}

⚡️ https://stackblitz.com/edit/github-sisqrx?file=src%2FApp.tsx
image

This is also just a difference between the timing of when setting state and navigate() will execute in the React lifecycle. State will update immediately, whereas navigate fires a side effect that eventually updates internal router state and gets pushed down via RouterProvider.

As @kiliman said, you should use one or the other so that the state changes are in sync. The search params from the URL make the most sense so that state can survive a page reload, but that's up to you.

This isn't a bug with the library, just a result of React's lifecycle vs the router's.

Hmm.. it looks like you're overcomplicating things. If you store state in search params, you don't need to store it in useState as well.

I think you missed the point... the important thing was to retrieve pageSize=10 from the url in the child component, not display=on, and update the pageSize accordingly (only in the url) if it contained an invalid value.

The issue is about the mismatch between calling navigate from a parent component and how a child component can not access immediately the queryString via setSearchParams (which is supposed to be a functional version). I would expect setSearchParams to behave like the functional version of setState, i.e. an updater function that on each update it provides the latest version of the queryString.
However, this is the behaviour of setState:

const [age, setAge] = useState(42);
function handleClick() {
  setAge(a => a + 1); // setAge(42 => 43)
  setAge(a => a + 1); // setAge(43 => 44)
  setAge(a => a + 1); // setAge(44 => 45)
}

and this is the behaviour of setSearchParams:

const [searchParams, setSearchParams] = useSearchParams();
function handleClick() {
  setSearchParams((prev) => {
    console.log(prev.toString()); // '' (empty string)
    const next = new URLSearchParams(prev);
    next.set('key1', 'value1');
    return next;
  });
  setSearchParams((prev) => {
    console.log(prev.toString()); // '' (empty string)
    const next = new URLSearchParams(prev);
    next.set('key2', 'value2');
    return next;
  });
  setSearchParams((prev) => {
    console.log(prev.toString()); // '' (empty string)
    const next = new URLSearchParams(prev);
    next.set('key3', 'value3');
    return next;
  });
 // after the render, searchParams.toString() will be 'key3=value3'
}

@timdorr if that is not a bug, you should make it clear in the documentation that it is not an actual updater function but something simpler.


Nevertheless, I have noticed that the loaders are called synchronously with every call to navigate or setSearchParams and, in fact, with the correct information (I can access the current url via the request field of its first argument).

See the code in the following link (I have removed the display=on from the url to avoid distraction with something irrelevant)
https://stackblitz.com/edit/github-mnf1bf?file=src%2Fapp.tsx

image