Skip to content

Instantly share code, notes, and snippets.

@gambala gambala/example.js
Created Jun 23, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.