Skip to content
Advertisement

Best way to remove empty query strings from an API request

In my react app I am tasked with sending multiple GET requests, sometimes with some optional filter params attached. Additionally I’m storing the params in my redux store so that they are able to stack on subsequent requests. Here’s the problem: There are times when I’ll clear the values of a param but since their keys are still saved to my store I’ll get requests sent out like this:

/restaurants/?search=&state_id=2

Notice how the search param value is empty (as expected). I was wondering what would be the best approach in removing these type of lingering params? I looked into lodash’s _.omitBy combined with _.isEmpty but this throws a sort of false positive in dealing with numeric values like pagination.

_.omitBy(params, ._isEmpty);

I didn’t think that providing how exactly the params are via react/redux was necessary stored but am happy to provide it if it helps.

Note: I’m using axios and passing my params in as an object as opposed to a string:

axios.get('restaurants', {
  params
});

Advertisement

Answer

Considering your params are stored in an object (as you mentioned in your latest edit), you can just remove properties containing empty strings:

const params = {
  search: "",
  state_id: 2
};

for (const key of Object.keys(params)) {
  if (params[key] === "") {
    delete params[key];
  }
}

console.info(params);

This alternative has the advantage of being short and easy to maintain.

But for those with a string containing all params already serialized, it’s easy to do using regular expressions:

function removeEmptyParams(query) {
  return query.replace(/[^=&]+=(?:&|$)/g, "");
}

const testQuery = "f=1&search=&state_id=2&foo=&bar=12";
console.info(removeEmptyParams(testQuery));

Also very simple and easy to maintain.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement