diox
Search…
diox/extensions/router
router is a diox module that automatically handles frontend routing and browser's history.

Getting started

1
// store.js
2
// --------------------------
3
import Store from 'diox';
4
import router from 'diox/extensions/router';
5
6
const store = new Store();
7
store.register('router', router([
8
'/home',
9
'/blog',
10
// Add all your app's routes here...
11
]));
12
export default store;
13
14
// main.js
15
// --------------------------
16
import store from './store.js';
17
18
store.subscribe('router', (context) => console.log(context));
Copied!
As any other diox modules, router must be registered into the store using the register method. As soon as it is done, any subscription to that module will receive the current routing context, containing useful information about current route.
1
{
2
host: 'mydomain.com', // Current app domain
3
params: { id: '125' }, // Route parameters
4
path: '/user/125', // Full route path (request URI)
5
protocol: 'http', // URL scheme (HTTP/HTTPS/...)
6
query: { q: 'ok' }, // Parsed query parameters (if any)
7
route: '/user/:id', // Route pattern that matched current URL
8
}
Copied!

Routing

When initializing the router module, a list of routes is expected in argument (see above). This list is actually a set of patterns that will be matched against the current URL. The matching process is based on the exact same logic as for the expressjs framework (using path-to-regexp npm package), which means you can define dynamic parameters in those routes, regular expressions, and so on. These dynamic info will be placed into the params key in the routing context.
Let's take an example. Imagine we initialized router this way.
1
store.register('router', router([
2
'/',
3
'/blog',
4
'/blog/posts/:name',
5
]));
Copied!
We are currently browsing the URL https://mydomain.com/blog/posts/diox-is-life
router will thus generate the following routing context.
1
{
2
host: 'mydomain.com',
3
params: { name: 'diox-is-life' },
4
path: '/blog/posts/diox-is-life',
5
protocol: 'https',
6
query: {},
7
route: '/blog/posts/:name', // `null` if no route matches the URL
8
}
Copied!

Navigation

One of the most interesting features of router is that you can navigate to any route seamlessly, without reloading the page, loosing current state or performing complex processing. Just call the NAVIGATE mutation.
1
store.mutate('router', 'NAVIGATE', '/my/next/page');
Copied!
router will automatically manage window's history, pushing a new state. The routing context will also be re-computed and dispatched to all subscriptions. It is especially useful when you want to track navigation, or to lazy load your app's pages over browsing, for instance, to improve initial page load. User can then go back and forth through his browser history as he usually would without breaking any logic or reloading page.
Last modified 1yr ago