0

I'm using react-router-4 and the corresponding react-router-redux for this version is not yet stable. I'm curious if there are ways I can access history from redux-observable epic. Example:

export function profileDropdownEpic (action$, { getState, dispatch }{
  return action$.ofType('SET_SELECTED_ITEM')
    .mapTo(() => {
      const selectedItem = getState().listDropdown.get('SelectedItem')
      if (selectedItem === 'logout') {
        history.push('/login')
      }  
      return {}
    })
}
anlogg
  • 1,050
  • 1
  • 15
  • 36

2 Answers2

2

When using epics, you want to include the History as a dependency of your EpicMiddleware. Dependencies are added as third argument to every epic.

Start out with creating the history.

import { createBrowserHistory } from 'history';
const history = createBrowserHistory();

When creating the EpicMiddleware, pass history as argument of the dependency object:

createEpicMiddleware({
  dependencies: { 
    history: history
  }
})

When creating the actual Epic, the third argument contains dependencies, of which one will be history.

const myEpic = (action, store, dependencies) => {
  // dependency.history.createHref(...)

  return action.pipe(...)
}

combineEpics(myEpic);
1

Create a history.js file that exports createHistory():

// history.js
import createHistory from 'history/createBrowserHistory'
export default createHistory()

Then import it in your epic:

// epics.js
import history from './history'     

export function profileDropdownEpic (action$, { getState, dispatch }){
  return action$.ofType('SET_SELECTED_ITEM')
    .mapTo(() => {
      const selectedItem = getState().listDropdown.get('SelectedItem')
      if (selectedItem === 'logout') {
        history.push('/login')
      }  
      return {}
  })
}

Don't forget to set the history props in your <Router />:

import history from './history'

<Router history={history}>...</Router>
Jaye Renzo Montejo
  • 1,812
  • 2
  • 12
  • 25