Created
June 23, 2017 14:45
-
-
Save gambala/18695bd738cd192206fad257feeb69fb to your computer and use it in GitHub Desktop.
Params filter and formatter for fetch requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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