Skip to content

Instantly share code, notes, and snippets.

@ccnokes
Last active June 17, 2018 03:42
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 ccnokes/1b06c5e70248b5ac4d8cc873312a24d6 to your computer and use it in GitHub Desktop.
Save ccnokes/1b06c5e70248b5ac4d8cc873312a24d6 to your computer and use it in GitHub Desktop.
`formatUrl` function that formats query params and such
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