Last active
March 6, 2018 06:41
-
-
Save andrey-helldar/8691ea5ad7ecd93d5a8571f60a1e33e5 to your computer and use it in GitHub Desktop.
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
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