Comments (3)
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
from react-router.
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.
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
from react-router.
Related Issues (20)
- [Bug]: React Router swallows render error HOT 1
- [Bug]: useBlocker in createBrowserRouter is not working
- [Bug]: useLocation value being null when 0 is set as the state value of useNavigate
- [Docs]: for useSearchParams, functional updates should be explained in more detail HOT 3
- [Bug]: React router doesn't handle 'content://' URLs
- [Bug]: the state is not destroyed in the useFetcher hook with key parametr HOT 1
- [Bug]: Outlet component remounts in production when changing state above it HOT 2
- [Bug]: loader of Route running even if Route / Router is not rendered HOT 2
- [Docs]: Docs for shouldRevalidate make it sound like it is only for opting out
- [Bug]: `useLocation` out of sync with `history.location`, leads to potential renders of unmatched `Route`s
- [Bug]: useLoaderData triggers component re rendering even if the route remains unchanged HOT 1
- [Bug]: Cloudflare Pages - Outlet not working. HOT 32
- [Bug]: No route matches URL in production build HOT 3
- [Bug]: <Outlet/> Component is not working in deployment HOT 1
- [Bug]: `window.location` is not updated after a call to `router.navigate()` HOT 1
- [Bug]: router doesn't work in production build, only shows blank. HOT 1
- [Bug]: `<Navigate>` can be canceled by `navigate("?x")` even if guarded by `if(navigation.state === "idle")` HOT 1
- [Bug]: Using embed in a route with param causes it to render the whole application inside the div. HOT 1
- [Docs]: V6 - Mixing up <Route /> with lists [<Route />, <Route />] within one <Routes /> looks working but isn't mentioned in the docs and covered in unit tests. HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from react-router.