Skip to content

Instantly share code, notes, and snippets.

@gambala
Created June 23, 2017 14:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gambala/18695bd738cd192206fad257feeb69fb to your computer and use it in GitHub Desktop.
Save gambala/18695bd738cd192206fad257feeb69fb to your computer and use it in GitHub Desktop.
Params filter and formatter for fetch requests
import urlWithParams from 'urlWithParams'
fetch(
urlWithParams('/api/v1/cities.json', {
name: input,
city_id: this.state.cityID,
})
)
.then((response) => response.json())
.then((json) => {
# code code code
})
import querystring from 'querystring';
const filterParams = (params) => {
return Object.keys(params)
.filter(key => !!params[key])
.reduce((r, key) => { r[key] = params[key]; return r; }, {})
}
const urlWithParams = (url, params) => {
const paramString = querystring.stringify(filterParams(params))
if (!paramString.length) return url;
return `${url}?${paramString}`;
}
export default urlWithParams;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment