〽️ MobX Router
v0.0.8 🎉 - by @thekitze
Example usage
Inspiration
📖 How to decouple state and UI - a.k.a. you don’t need componentWillMount
Features
- Decoupled state from UI
- Central route configuration in one file
- URL changes are triggering changes directly in the store, and vice-versa
- No need to use component lifecycle methods like
componentWillMount
to fetch data or trigger a side effect in the store - Supported hooks for the routes are:
beforeEnter
,onEnter
,beforeExit
,onExit
. All of the hooks receiveroute
,params
,store
, andqueryParams
as parameters. If thebeforeExit
orbeforeEnter
methods returnfalse
the navigation action will be prevented. - The current URL params and query params are accessible directly in the store
store.router.params
/store.router.queryParams
so basically they're available everywhere without any additional wrapping or HOC. - Navigating to another view happens by calling the
goTo
method on the router store, and the changes in the url are reflected automatically. So for example you can callrouter.goTo(views.book, {id:5, page:3})
and after the change is made in the store, the URL change will follow. You never directly manipulate the URL or the history object. <Link>
component which also populates the href attribute and works with middle click orcmd/ctrl
+ click
Implementation
;;; ;; //example mobx storeconst store = app: title: 'MobX Router Example App' user: null //here's how we can plug the routerStore into our store router: ; ; ReactDOM
Example config
/config/views.js
; //models; //components;;;;; const views = home: path: '/' component: <Home/> userProfile: path: '/profile/:username/:tab' component: <UserProfile/> { console; } { console; } { console; } gallery: path: '/gallery' component: <Gallery/> { storegallery; console; } { const result = ; return result; } document: path: '/document/:id' component: <Document/> { const userIsLoggedIn = storeappuser; if !userIsLoggedIn ; return false; } { console; } book: path: '/book/:id/page/:page' component: <Book/> { console; storeapp; } ;;
ToDo
- Add async support for the
beforeEnter
andbeforeExit
hooks - Add array support for the hooks so they can execute multiple methods. A sample usage of this would be having one
isUserAuthenticated
method that can be just plugged in as one of the callbacks triggered from the hook.