Search code examples
reactjsreact-routerstorereact-reduxhistory

React-router-redux error when creating store with middleware


I'm new to react-redux and trying to follow a tutorial that is a bit old, so when i try running this code i get error:

Uncaught Error: Expected the routing state to be available either as state.routing or as the custom expression you can specify as selectLocationState in the syncHistoryWithStore() options. Ensure you have added the routerReducer to your store's reducers via combineReducers or whatever method you use to isolate your reducers.

Any tips? :)

index.js

import React from 'react'
import ReactDOM from "react-dom"
import { createStore, applyMiddleware } from 'redux'
import { Provider } from 'react-redux'
import { Router, Route, browserHistory } from 'react-router'
import { syncHistoryWithStore, routerReducer } from 'react-router-redux'
import App from './containers/App'
import rootReducer from './reducers/reducers'
import thunkMiddleware from 'redux-thunk'
import api from './middleware/api'

let createStoreWithMiddleware = applyMiddleware(thunkMiddleware, api)(createStore)

let store = createStoreWithMiddleware(rootReducer)

let history = syncHistoryWithStore(browserHistory, store)

let rootElement = document.getElementById('root')

ReactDOM.render(
  <Provider store={store}>
    <Router history={history}>
      <Route path='/' component={App} />
    </Router>
  </Provider>,
  rootElement
)

my reducers.js looks like this:

import { combineReducers } from 'redux'

import Auth from './auth'
import Quotes from './quotes'

const rootReducer = combineReducers({
    auth: Auth,
    quotes: Quotes
})

export default rootReducer

Solution

  • You must add the routerReducer() for syncing to work in react-router-redux.

    This reducer function stores location updates from history. If you use combineReducers, it should be nested under the routing key.

    Include the following in your combine reducers.

    import { routerReducer } from 'react-router-redux';
    
    export const reducers = combineReducers({
      ...  // other reducers
      routing: routerReducer
    });
    

    So your reducers file looks like:

    import { routerReducer } from 'react-router-redux';
    import { combineReducers } from 'redux'
    
    import Auth from './auth'
    import Quotes from './quotes'
    
    const rootReducer = combineReducers({
        auth: Auth,
        quotes: Quotes,
        routing: routerReducer
    })
    
    export default rootReducer