diff --git a/README.md b/README.md index d2be745..3e471bf 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,19 @@ Pass a rails-style path and an object containing values for any route parameters Match a literal `path` (no colons) against all routes and dispatch the matching action, passing in route parameters. `path` defaults to `window.location.hash` with leading and trailing slashes stripped out. +## `redirect` + +Redirect the user to a different route instead of dispatching an action. This is useful anytime a +redirects is desired, such as an old route being deprecated. + +```JavaScript +import createRouter, { redirect } from '@density/conduit'; +import store from './store'; + +const router = createRouter(store); +router.addRoute('foo/bar', redirect('hello/world')); +router.addRoute('hello/world', () => ({type: "NAVIGATE_TO_HELLO_WORLD"}) ); +``` ## Development diff --git a/index.js b/index.js index 1e91f05..abbfa7e 100644 --- a/index.js +++ b/index.js @@ -25,8 +25,11 @@ export function handle(routes, store, path) { path = path || window.location.hash.slice(1).replace(/(^\/|\/$)/, ''); var route = checkPath(routes, path); if (route) { - var params = route.regexp.exec(path).slice(1); - store.dispatch(route.action.apply(route, params)); + const params = route.regexp.exec(path).slice(1); + const action = route.action.apply(route, params); + if (action) { + store.dispatch(action); + } return true; } else { console.warn('Route to ' + path + ' not found!'); @@ -34,6 +37,12 @@ export function handle(routes, store, path) { } } +export function redirect(url) { + return () => { + window.location.href = url; + } +} + // Programmatically "navigate" (just sets window.location.hash) export function navigate(routes, path, params) { var route = checkPath(routes, path);