Redux-based routing with Rudy
Tags: react, routing, redux, reduxtoolkit
Published: 2021-02-14 15:55:35

---
title: Redux-based routing with Rudy
published: true
description: 
tags: React, Routing, Redux, ReduxToolkit
//cover_image: https://direct_url_to_image.jpg
---
### Why

With the recent release of Redux Toolkit, redux and its related libraries have become easier than ever to integrate into react applications. I've always enjoyed using redux as a state management tool because, despite its verbosity, it always boiled down to simple actions and reducers. I've stuffed many things into redux, for better or for worse, and one of the things I still feel is for the better is routing.

I don't really have any strong arguments as to why one should put routing state in redux rather than components. They both work. I just find it simpler when routing plays nice with redux. 

### What

[`Rudy`](https://github.com/respond-framework/rudy) is a redux-based router and the successor to `redux-first-router`. At its core, it uses redux actions to manage your routing state. Actions are used to change pages, actions are used to bind to urls, actions are used to bind to components, and everything else related to routing. Once set up, this is what creating and using a route looks like in `rudy`:

```JS
// page.slice.ts
import { createAction } from '@reduxjs/toolkit';

export const toHelp = createAction('page/toHelp');

// home.component.ts
import { useDispatch } from 'react-redux';
import { toHelp } from './page.slice';

const Home = () => {
	const dispatch = useDispatch()

  return (
    <div>
      <p>This is the Home page</p>
      <button onClick={() => dispatch(toHelp())}>Help</button>
    </div>
  )
}
```

An action creator is created and then it is dispatched in the `Home` component upon a button click, which will then route the user to the `Help` page (this is a simplified example). 

Because the routing is based entirely on redux actions, you can dispatch route changes anywhere in your app where would normally dispatch redux actions. This can come in handy not only in components and event handlers but also in redux middleware where you might to dispatch a route change in response to an async action:

```js
// page.epic.ts
export const redirectToHelpEpic = (
  action$: ActionsObservable<PayloadAction>,
  state$: StateObservable<StoreState>,
): Observable<PayloadAction> =>
  action$.pipe(
    filter(storeLocationUpdateSuccess.match),
    map((_) => {
      return toHelp();
    }),
  );
```

In the above example, I redirect to the `Help` page after a successful async update using `redux-observables`. The same idea can be applied to other types of middleware like `thunks` or `sagas`.

### How (part 1)

Every redux app needs to configure a store, and that task has been made easier thanks to the recent addition of Redux toolkit:

```js
// store.ts
import { configureStore as configureReduxStore } from '@reduxjs/toolkit';
import { createRouter } from '@respond-framework/rudy';

// We'll get to these routes later
import { urlRoutes, pageReducer } from 'modules/page';

export const configureStore = () => {
  const { reducer: locationReducer, middleware: routerMiddleware, firstRoute } = createRouter(urlRoutes);

  const store = configureReduxStore({
    reducer: {
      location: locationReducer,
			page: pageReducer
    },
    middleware: [
      routerMiddleware,
    ],
  });

  return { store, firstRoute };
};
```

`rudy` provides a `reducer`, `middleware`, and `firstRoute`. The first two objects hook into the redux store while the `firstRoute` is a little oddity that needs to be dispatched before the app is rendered. Plugging it into your component tree can look like this:

```js
// index.tsx

const { store, firstRoute } = configureStore();

function render() {
  ReactDOM.render(
      <ReduxProvider store={store}>
        <React.StrictMode>
          <App />
        </React.StrictMode>
      </ReduxProvider>
    document.getElementById('root'),
  );
}

store.dispatch(firstRoute()).then(() => render());
```

These steps setup `rudy` for use in our store. Now we can create our own little `redux` slice and configure the actions that `rudy` will watch and bind to in order to manage routing.

### How (part 2)

Like any other `redux` slice, we're going to need actions, reducers, and selectors. But in order to bind our actions to urls and components we're also going to create a couple more mapping objects:

```js
// modules/page/page.slice.ts
import { createSlice, createSelector, createAction } from '@reduxjs/toolkit';

// Our action creators
export const toOrders = createAction('page/toOrders');
export const toHelp = createAction('page/toHelp');
export const toSettings = createAction('page/toSettings');
export const toManagePlan = createAction('page/toManagePlan');
export const toNotFound = createAction('page/toNotFound');

// Mapping actions to routes (used in rudy initialization)
export const urlRoutes = {
  [toOrders.toString()]: '/orders',
  [toHelp.toString()]: '/help',
  [toSettings.toString()]: '/settings',
  [toManagePlan.toString()]: '/manage-plan',
  [toNotFound.toString()]: '/not-found',
};

// Mapping actions to components (note that the values must match the names of the components)
export const componentRoutes = {
  [toOrders.toString()]: 'Orders',
  [toHelp.toString()]: 'Help',
  [toSettings.toString()]: 'Settings',
  [toManagePlan.toString()]: 'ManagePlan',
  [toNotFound.toString()]: 'NotFound',
};

// An array of all our action types for convenience
export const routeActionTypes = [
  toOrders.toString(),
  toHelp.toString(),
  toSettings.toString(),
  toManagePlan.toString(),
  toNotFound.toString(),
];

// Our redux slice
const pageSlice = createSlice({
  name: 'page',
  initialState: {
    currentPage: componentRoutes[toHelp.toString()],
  },
  reducers: {},
  extraReducers: Object.fromEntries(
    routeActionTypes.map((routeActionType: string) => {
      return [
        routeActionType,
        (state: any, action) => {
          state.currentPage = componentRoutes[action.type];
        },
      ];
    }),
  ),
});

const { reducer } = pageSlice;

export const pageReducer = reducer;

// selectors
export const selectPage = (state: StoreState): PageState => {
  return state.page;
};

export const selectLocation = (state: StoreState): LocationState => {
  return state.location;
};

export const selectCurrentPage = createSelector(
  selectPage,
  (pageState) => pageState.currentPage,
);

```

And now we're good to go. Our routes are synced and tracked to redux and we can use them in our components like this:

```js
// pages/index.ts
export { Orders } from './orders';
export { PickupAndDelivery } from './pickup-and-delivery';
export { Help } from './help';
export { Settings } from './settings';
export { ManagePlan } from './manage-plan';
export { NotFound } from './not-found';

// app.component.tsx
import React from 'react';
import { useDispatch } from 'react-redux';
import { DesignSystemProvider, Page } from '@SomeDesignSystem';
import { useSelector } from 'react-redux';

import { selectCurrentPage } from 'modules/page';
import * as pages from 'pages';

export const App = () => {
  const dispatch = useDispatch();

  const currentPage = useSelector(selectCurrentPage);
  const Component = pages[currentPage];

  return (
    <DesignSystemProvider>
      <Page>
        <Component />
      </Page>
    </DesignSystemProvider>
  );
};
```

The current page can be queried for and updated by using actions and selectors from the `page` slice we created, and any routing-related data can be found in the `location` reducer provided by `rudy`, which can also be queried for as any other redux reducer. 

### Gotchas

You may want to integrate url parameters at some point in your development, and you may find that `rudy` and `redux` don't play nice together out of the box. 

You can create actions and routes that use parameters like this:

```js
export const toManageLocation = createAction('page/toManageLocation', function prepare(locationId: string) {
  return {
    payload: {
      locationId,
    },
  };
});

export const urlRoutes = {
  [toManageLocation.toString()]: '/manage-location/:locationId',
};
```

But Redux toolkit requires actions to have a `payload` property while `rudy` actions use a `params` property instead when it comes to parameters. The good news is that it's all redux and it can be fixed with redux tools, namely redux middleware. I worked around this issue by creating a middleware that converts the `payload` from routing-specific actions to `params` so that `rudy` and `RTK` can play nice together again. 

```js
const rudyActionPayloadToParamsConverter = (store: any) => (next: any) => (action: any) => {
  const shouldConvert = routeActionTypes.includes(action?.type) && !!action?.payload;

  if (shouldConvert) {
    const nextAction = {
      type: action?.type,
      params: action?.payload,
    };
    return next(nextAction);
  }

  return next(action);
};

const store = configureReduxStore({
    reducer: {
      ...
    },
    middleware: [
      rudyActionPayloadToParamsConverter,
      routerMiddleware,
      epicMiddleware,
    ]
  });
```

### Conclusion

Routing state can easily be integrated into and managed by redux thanks to `rudy`. If you're looking for a router designed for redux, I highly recommend this library. Though the documentation may be lacking and it's popularity is nowhere near more popular routing libraries, it works just fine.