useSearchParams not updating when using useNavigate #11424
-
When using
You'll see that the |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
I'm not sure I fully understand your example, but it looks like you want to navigate to the the route after the search params are updated. You don't have to use Here's an example where you can check multiple categories and each time, it will update the search params and navigate/re-render.` const categories = ['Meats', 'Dairy', 'Fruits', 'Vegetables', 'Bread'];
function Home() {
let [searchParams, setSearchParams] = useSearchParams();
let location = useLocation();
let data = {
location: `${location.pathname}${location.search}`,
params: {
category: searchParams.getAll('category'),
},
};
const handleClick = (e) => {
const category = e.target.value;
if (searchParams.has('category', category)) {
searchParams.delete('category', category);
} else {
searchParams.append('category', category);
}
setSearchParams(searchParams);
};
return (
<div>
<h2>Home</h2>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{categories.map((category) => (
<label key={category}>
<input
type="checkbox"
name="category"
value={category}
checked={searchParams.has('category', category)}
onClick={handleClick}
/>
{category}
</label>
))}
</div>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
} ⚡️ StackBlitz https://stackblitz.com/edit/github-sisqrx?file=src%2FApp.tsx 📖 MDN https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams |
Beta Was this translation helpful? Give feedback.
-
The replacement functions worked for me, but I was starting the project in create react app so upgrading didn't work at first. I had to switch the project over to |
Beta Was this translation helpful? Give feedback.
The 2-param version of
URLSearchParams.has
and.delete
were introduced in Node.js v20.2.0, v18.18.0https://nodejs.org/api/url.html#urlsearchparamshasname-value
As for browser compatibility
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/has
If you can't upgrade, then here are replacement functions: