Skip to content

Instantly share code, notes, and snippets.

@SpaceK33z
Last active January 23, 2018 10:31
Show Gist options
  • Save SpaceK33z/9878b6a193daf9baa012a08e8822d8d3 to your computer and use it in GitHub Desktop.
Save SpaceK33z/9878b6a193daf9baa012a08e8822d8d3 to your computer and use it in GitHub Desktop.
mobx-spine url param binding pseudocode
class MyScreen extends Component {
componentWillMount() {
this.store = new Store();
this.urlParamBinding = UrlParamBinding(this.store, {
// This are the default props
});
}
componentWillUnmount() {
if (this.urlParamBinding) {
this.urlParamBinding();
}
}
}
function UrlParamBinding(store, defaultParams) {
store.params = defaultParams;
let urlParams = new URLSearchParams(window.location.search);
urlParams = fromPairs(Array.from(urlParams.entries()));
if (isEmpty(urlParams)) {
store.params = defaultParams;
} else {
store.params = urlParams;
}
// Doesn't matter if fetch is done in willmount or didmount, that's just something I made up once.
this.fetch();
// By returning this you can easily unsubscribe in the screen
return autorun(() => {
const p = new URLSearchParams(toJS(store.params));
window.history.replaceState({}, '', `${window.location.pathname}?${p}`);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment