Giter Site home page Giter Site logo

mst-react-router's Introduction

mst-react-router

Keep your mobx-state-tree state in sync with react-router via a RouterModel.

This library provides a RouterModel model which can instantiated and composed as part of your root app store.

This library is for use with react-router v4.

Installation

npm install --save mst-react-router

And if you haven't installed all the peer dependencies, you should probably do that now:

npm install --save mobx-state-tree mobx mobx-react react-router

Usage

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import createBrowserHistory from 'history/createBrowserHistory';
import { Provider } from 'mobx-react';
import { Router } from 'react-router';
import { types } from 'mobx-state-tree';
import { RouterModel, syncHistoryWithStore } from 'mst-react-router';

import App from './App';

const routerModel = RouterModel.create();

// Define root model type
const Model = types.model({
  router: RouterModel
});

export const store = Model.create({ router: routerModel });

// Hook up router model to browser history object
const history = syncHistoryWithStore(createBrowserHistory(), routerModel);

ReactDOM.render(
  <Provider store={store}>
    <Router history={history}>
      <App />
    </Router>
  </Provider>,
  document.getElementById('root')
);

App.js

import React, { Component } from 'react';
import { inject, observer } from 'mobx-react';
import { withRouter } from 'react-router';

class App extends Component {
  render() {
    const { location, push, goBack } = this.props.store.router;

    return (
      <div>
        <span>Current pathname: {location.pathname}</span>
        <button onClick={() => push('/test')}>Change url</button>
        <button onClick={() => goBack()}>Go Back</button>
      </div>
    );
  }
}

// withRouter helps avoid update "block" issues
export default withRouter(inject('store')(App));

Troubleshooting

Routes not updating correctly when URL changes

There is a known issue with React Router 4 and MobX (and Redux) where "blocker" components like those created by @observer (and @connect in Redux) block react router updates from propagating down the component tree.

There is a React Router 4 documentation page for information on this issue:

https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/guides/blocked-updates.md

To fix problems like this, try wrapping components which are being "blocked" with React Router's withRouter higher order component should help, depdending on the case.

Refer to the link above for more information on this solution, and some alternatives.

API

RouterModel

const routerModel = RouterModel.create();

A RouterModel instance has the following properties:

And the following history methods, which all have the same signatures as listed on the history API page (follow the link).

push(path, [state]) replace(path, [state]) go(n) goBack() goForward() block(prompt)

syncHistoryWithStore(history, store)

  • history - A variant of a history object, usually browserHistory
  • store - An instance of RouterModel

returns an enhanced history object with the following additional method:

  • unsubscribe()
    Un-syncs the store from the history. The store will no longer update when the history changes.
const history = syncHistoryWithStore(createBrowserHistory(), routingModel);
history.unsubscribe();
// Store no longer updates

mst-react-router's People

Contributors

alisd23 avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.