Skip to content

Instantly share code, notes, and snippets.

@andrey-helldar
Last active March 6, 2018 06:41
Show Gist options
  • Save andrey-helldar/8691ea5ad7ecd93d5a8571f60a1e33e5 to your computer and use it in GitHub Desktop.
Save andrey-helldar/8691ea5ad7ecd93d5a8571f60a1e33e5 to your computer and use it in GitHub Desktop.
const queryString = require('query-string');
export default class UrlParams {
static urlOptions() {
return {
arrayFormat: 'bracket'
};
};
static set(params) {
let uri = window.location.origin + window.location.pathname;
let query = this.encodeURI(params);
history.pushState(null, null, (uri + '?' + query));
}
static encodeURI(obj) {
return queryString.stringify(obj, this.urlOptions);
}
static decodeURI(uri) {
let params = queryString.parseUrl(uri, this.urlOptions).query;
_.each(params, (value, key) => {
try {
_.set(params, key, JSON.parse(value));
} catch (e) {
}
});
return params;
}
}
// Using:
// import UrlParams from './urlParams';
// window.urlParams = UrlParams;
//
// urlParams.encodeURI({page: 2, sort: 'desc});
// urlParams.decodeURI('http://mysite.local/?page=2&sort=desc');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment