Last active
January 23, 2018 10:31
-
-
Save SpaceK33z/9878b6a193daf9baa012a08e8822d8d3 to your computer and use it in GitHub Desktop.
mobx-spine url param binding pseudocode
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
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