0

I found https://stackoverflow.com/a/73353425/21065649 which basically uses useSearchParams from react-router-dom to remove query string parameters.

However, in my case, I'm using an array of keys and I have to loop over them to remove params.

The problem is case sensitivity.

const [searchParams, setSearchParams] = useSearchParams();
const keys = ['Title', 'State']
for (let index in keys) {
   if (searchParams.has(keys[index]) {   // I want this to be case-insensitive
      seearchParams.delete(keys[index])
   }
}

I don't know how to do that.

1 Answers1

1

Use .filter() instead. The result of the filter is an array of keys that are not in the keys array (i.e. Title and State).

You should call setSearchParams after the filter is applied, like this:

const [searchParams, setSearchParams] = useSearchParams();
const keys = ['Title', 'State']

const filteredParams = searchParams.filter((key) => !keys.includes(key.toLowerCase()));
filteredParams.forEach((key) => searchParams.delete(key));
setSearchParams(searchParams);

EDIT: Non-array entries

If 'searchParams' is not an array, you can call the Object.keys() method on searchParams which will return an array of keys, then you can use the filter() method on that array.

const [searchParams, setSearchParams] = useSearchParams();
const keys = ['Title', 'State']

const filteredParams = Object.keys(searchParams).filter((key) => !keys.includes(key.toLowerCase()));
filteredParams.forEach((key) => searchParams.delete(key));
setSearchParams(searchParams);
Juan Melnechuk
  • 461
  • 1
  • 8
  • Can you please make your code more complete? What is the result of that `filter`? Where should I call `setSearchParams`? – Atefeh Jahanshahi Feb 19 '23 at 12:24
  • filteredParams has an array of keys that are not in the keys array (i.e. Title, tItlE, TITLE or State, STatE). Call setSearchParams after the filter is applied (updated answer) – Juan Melnechuk Feb 19 '23 at 12:29
  • I get the `searchParams.filter is not a function` error. – Atefeh Jahanshahi Feb 19 '23 at 12:45
  • The likely cause of this is that 'searchParams' is not an array. Change filteredParams var with ```const filteredParams = Object.keys(searchParams).filter((key) => !keys.includes(key.toLowerCase()));``` – Juan Melnechuk Feb 19 '23 at 12:48