-
-
Notifications
You must be signed in to change notification settings - Fork 10.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Bug]: setSearchParams
do not provide the latest queryString passed as argument to navigate
#11431
Comments
setSearchParams
do not provide an updatedsearchParams
setSearchParams
do not provide an updated queryString
setSearchParams
do not provide an updated queryStringsetSearchParams
do not provide the latest queryString
setSearchParams
do not provide the latest queryStringsetSearchParams
do not provide the latest queryString passed as argument to navigate
Hmm.. it looks like you're overcomplicating things. If you store state in search params, you don't need to store it in 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 |
This is also just a difference between the timing of when setting state and 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. |
I think you missed the point... the important thing was to retrieve The issue is about the mismatch between calling 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 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 See the code in the following link (I have removed the |
What version of React Router are you using?
6.22.3
Steps to Reproduce
Expected Behavior
When the
showGenericComponent( )
method is called:setDisplay(true)
andnavigate({ search: '?display=on&pageSize=10' })
.GenericComponent
to be displayed and in turn theuseEffect
it contains to be executed.I expect that the functional version of
setSearchParams
(used within theuseEffect
) to provide a searchParams containing?display=on&pageSize=10
, which was the argument passed to thenavigate
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 callingnavigate
).I have seen that you could get the actual value of the queryString in the
loader
, and could therefore add such logic in theloader
or derive it from theloader
. However, I would expect that the functional version ofuseSearchParams
to provide the latest version of the queryString.The text was updated successfully, but these errors were encountered: