admin管理员组文章数量:1296308
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
bined 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
});
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
bined 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
});
Share
edited Nov 26, 2019 at 19:56
Carl Edwards
asked Nov 26, 2019 at 18:59
Carl EdwardsCarl Edwards
14.5k12 gold badges66 silver badges131 bronze badges
5 Answers
Reset to default 5Considering 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.
The best and easiest way is to use a Spread Object literal on every optional param, like this
params:{
...( CONDITION && {param_key: param_value}),
...( this.state_id != null && {state_id: this.state_id})
}
If condition is TRUE, the encapsulated key:value pair will be unwrapped, if condition is false , there will be no empty value or key.
You might need to parse that manually. Split on the &
then split on the =
and check if there's a value based on the length of the split - remove accordingly from there. If you're fortable with regex you can check if there are values after the =
instead of splitting.
This solution is a little crude, but it works. Let's assume your query params are stored in a Map, something like:
const params = {
foo: 'bar',
bang: 0,
buzz: '' // this value has been removed from your store
}
You could create an array of keys from your params Map, filter out the items that don't have a value and then join them all back together as query params.
const queryString = Object.keys(params).map(filter => {
if (params[filter] || Number.isInteger(params[filter])) {
return `${filter}=${params[filter]}`;
}
return null;
}).filter(item => item).join('&');
Which would result in foo=bar&bang=0
I suppose there is a possibility to use package like "queryString". It removes empty search params form url string
import queryString from 'query-string';
const queryParams = queryString.stringify({ filters, sort: sortParams, offset: PRODUCT_OFFSET, limit: PRODUCT_LIMIT });
const urlProductList = `${BASE_URL}/country/${countryCode}/group/${groupID}/product?${queryParams}`;
本文标签: javascriptBest way to remove empty query strings from an API requestStack Overflow
版权声明:本文标题:javascript - Best way to remove empty query strings from an API request - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741617893a2388635.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论