Git Product home page Git Product logo

Comments (3)

kiliman avatar kiliman commented on May 1, 2024

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

from react-router.

timdorr avatar timdorr commented on May 1, 2024

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.

from react-router.

jean-leclerc avatar jean-leclerc commented on May 1, 2024

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

from react-router.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.