Last active
June 17, 2018 03:42
-
-
Save ccnokes/1b06c5e70248b5ac4d8cc873312a24d6 to your computer and use it in GitHub Desktop.
`formatUrl` function that formats query params and such
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 * as _ from 'lodash'; | |
let n = 2; | |
let someString; | |
// NOTE `_.pickBy(params, _.negate(_.isNil))` removes undefined/null entries | |
// so you don't have to worry about `undefined` getting coerced to a string | |
const formatUrl = (urlStr, params) => urlStr + '?' + | |
new URLSearchParams(_.pickBy(params, _.negate(_.isNil))).toString(); | |
fetch(formatUrl('/endpoint', { | |
foo: n > 1 ? 123 : 456, | |
bar: '1%', // this gets encoded automatically | |
query: someString // this entry gets removed because it's undefined | |
})); | |
// the formatted URL is "/endpoint?foo=123&bar=1%25" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment