Skip to content

Instantly share code, notes, and snippets.

@damaon
Created January 6, 2018 01:32
Show Gist options
  • Select an option

  • Save damaon/8ff6101a1a9601b76547c64232588048 to your computer and use it in GitHub Desktop.

Select an option

Save damaon/8ff6101a1a9601b76547c64232588048 to your computer and use it in GitHub Desktop.
import UniversalRouter from 'universal-router';
const routes = [
{
path: '', // optional
action: () => `<h1>Home</h1>`,
},
{
path: '/posts',
action: () => console.log('checking child routes for /posts'),
children: [
{
path: '', // optional, matches both "/posts" and "/posts/"
action: () => `<h1>Posts</h1>`,
},
{
path: '/:id',
action: (context) => `<h1>Post #${context.params.id}</h1>`,
},
],
},
];
const router = new UniversalRouter(routes);
const redirect = (path, push = true) => {
router.resolve(path).then(html => {
const from = window.location.pathname;
const to = path;
console.log("redirect", from, to);
if(push)window.history.pushState(to, '', to);
document.body.innerHTML = html; // renders: <h1>Posts</h1>
}, (error) => {
document.body.innerHTML = '404 not found :/';
});
}
redirect(window.location.pathname);
window.onpopstate = function () {
redirect(window.location.pathname, false);
};
window.setTimeout(() => redirect("/posts/123"), 3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment