@sigfox/redux-router-transitions-middleware

1.1.3 • Public • Published

redux-router-transitions-middleware

Redux middleware for @sigfox/redux-router handling API calls during routes transitions

Features

When the route changes (@sigfox/redux-router), the middleware checks if the React component associated to the new route has static method "fetchDataDeferred" and calls it.

Install

npm install @sigfox/redux-router-transitions-middleware

Usage

import React from 'react';
import { createStore, combineReducers, compose, applyMiddleware } from 'redux';
import createHistory from 'history/lib/createMemoryHistory';

import { Route } from '@sigfox/react-router';
import { reduxReactRouter, routerStateReducer, push } from '@sigfox/redux-router';
import transitionsMiddleware from '@sigfox/redux-router-transitions-middleware';

const INIT_COMPONENT = 'INIT_COMPONENT';

class FirstComponent extends React.Component {
  static fetchDataDeferred = ({ dispatch }) =>
    dispatch({
      type: INIT_COMPONENT,
      data: 1
    });

  render = () => <div>First component</div>;
}

const routes = (
  <Route path="/">
    <Route path="first" component={FirstComponent} />
  </Route>
);

const componentReducer = (state = {}, action) => {
  switch (action.type) {
    case INIT_COMPONENT:
      return { data: action.data };
    default:
      return state;
  }
};

const reducer = combineReducers({
  router: routerStateReducer,
  component: componentReducer
});

const store = compose(
  reduxReactRouter({
    routes,
    createHistory
  }),
  applyMiddleware(transitionsMiddleware)
)(createStore)(reducer);

// This will trigger a rerouting to /first, since the component has the method "fetchDataDeferred", the
// action 'INIT_COMPONENT' will be dispatched and the value of data in the component reducer will change.
store.dispatch(push({ pathname: '/first' }));

Test

npm test

Licence

This project is licensed under the MIT License - see the LICENSE file for details.

Package Sidebar

Install

npm i @sigfox/redux-router-transitions-middleware

Weekly Downloads

2

Version

1.1.3

License

MIT

Unpacked Size

36.1 kB

Total Files

8

Last publish

Collaborators

  • robnriks
  • cgrimal
  • damien-s
  • lbdremy