From 9f282730cfbe123324866b8ef374fada490a6b2f Mon Sep 17 00:00:00 2001 From: Ryan Gaus Date: Mon, 7 May 2018 10:04:31 -0400 Subject: [PATCH 1/2] code: add `redirect` helper ``` import createRouter, { redirect } from '@density/conduit'; const router = createRouter(store); router.addRoute('foo/bar', redirect('hello/world')) router.addRoute('hello/world', () => ({type: "NAVIGATE_TO_HELLO_WORLD"}) ) ``` --- README.md | 13 +++++++++++++ index.js | 13 +++++++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d2be745..53bf03d 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 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); From ca661bc84529d7bddca8b39be67bb3c23115a5b5 Mon Sep 17 00:00:00 2001 From: Ryan Gaus Date: Wed, 30 May 2018 07:58:28 -0400 Subject: [PATCH 2/2] chore: forgot to import `redirect` --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 53bf03d..3e471bf 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ Redirect the user to a different route instead of dispatching an action. This is redirects is desired, such as an old route being deprecated. ```JavaScript -import createRouter from '@density/conduit'; +import createRouter, { redirect } from '@density/conduit'; import store from './store'; const router = createRouter(store);