React-Router v4 + Redux-Saga navigation
Asked Answered
T

3

10

I am trying to move user after successfull authentication process (after login / register) however it looks like every solution which I found on the internet - stackoverflow / github issues / medium etc - doesnt work!

please find my code below.

import { call, put, takeLatest } from 'redux-saga/effects'
import { push } from 'react-router-redux'

import { USER_LOGIN_SUCCEEDED, USER_LOGIN_FAILED, USER_LOGIN_REQUESTED } from '../actions/types'

import { login } from '../api'

function * loginUser (action) {
  try {
    const token = yield call(login, action.payload.email, action.payload.password)
    yield put({type: USER_LOGIN_SUCCEEDED, token: token})
    yield put(push('/dashboard'))
  } catch (error) {
    yield put({type: USER_LOGIN_FAILED, error: error.message})
  }
}

function * loginSaga () {
  yield takeLatest(USER_LOGIN_REQUESTED, loginUser)
}

export default loginSaga

not sure if its necessary but I will paste my router code as well

    import React from 'react'
import { Route } from 'react-router-dom'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'

import ForgotPasswordForm from './components/home-page/ForgotPasswordForm'
import LoginForm from './components/home-page/LoginForm'
import RegisterForm from './components/home-page/RegisterForm'
import ResetPasswordForm from './components/home-page/ResetPasswordForm'

import Dashboard from './containers/Dashboard'
import HomePage from './containers/HomePage'

import PrivateRoute from './helpers/privateRoute'

import './index.scss'

class App extends React.Component {
  componentDidMount () {
    const token = window.localStorage.token
    if (token) {
      this.props.dispatch({type: 'USER_LOGIN_SUCCEEDED', token: token})
    }
  }

  render () {
    return (
        <div>
          <Route exact path='/' component={HomePage} />
          <Route path='/login' component={LoginForm} />
          <Route path='/register' component={RegisterForm} />
          <Route path='/forgot-password' component={ForgotPasswordForm} />
          <Route path='/reset-password/:resetPasswordToken' component={ResetPasswordForm} />
          <PrivateRoute path='/dashboard' component={Dashboard} />
        </div>
    )
  }
}

App.propTypes = {
  dispatch: PropTypes.func.isRequired
}

export default connect()(App)

and finally index.js code

import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore, applyMiddleware, compose } from 'redux'
import createSagaMiddleware from 'redux-saga'
import { ConnectedRouter, routerMiddleware } from 'react-router-redux'
import createHistory from 'history/createBrowserHistory'

import App from './App.js'

import rootReducer from './reducers/rootReducer'
import setAuthorizationToken from './helpers/setAuthorizationToken'
import loginSaga from './sagas/loginSaga'
import registerSaga from './sagas/registerSaga'

const sagaMiddleware = createSagaMiddleware()

const history = createHistory()

const reduxRouterMiddleware = routerMiddleware(history)

const store = createStore(
  rootReducer,
  compose(
    applyMiddleware(sagaMiddleware, reduxRouterMiddleware),
    window.devToolsExtension ? window.devToolsExtension() : f => f
  )
)

sagaMiddleware.run(registerSaga)
sagaMiddleware.run(loginSaga)

if (window.localStorage.token) {
  setAuthorizationToken(window.localStorage.token)
}

render(
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <App />
    </ConnectedRouter>
  </Provider>,
  document.getElementById('app')
)

Any idea why Its not working? I also tried to import browserHistory in saga file and use something like yield browserHistory.push('/dashboard')

Every help will be highly appreciated.

little update - I am receiving this error now enter image description here

Tifanie answered 16/1, 2018 at 18:37 Comment(3)
You can pass your context to your saga or your history to your sagaCapriccioso
how can you do that via context?Tifanie
You can take a look at this : github.com/strapi/strapi-examples/tree/master/login-react/… it's an example app that shows one way to implement the authentication flowCapriccioso
J
3

You don't have react-router-redux set up fully (https://github.com/ReactTraining/react-router/tree/master/packages/react-router-redux)

You need

  • ConnectedRouter
  • Router reducer
  • Router middleware

Otherwise redux doesn't know what to do with the push action - no reducer or middleware knows that action, so they ignore it.

Joettejoey answered 16/1, 2018 at 23:25 Comment(1)
Alex thanks for your participation, I just updated the code (updated my post aswell) but its still doesnt work - can you have a look please?Tifanie
O
5

You can use createHistory from history package. passing it to react-router and accessing it in sagas.

/** history.js ****/
import {createBrowserHistory} from 'history'

export default createBrowserHistory({your_config_here})

/** saga.js ***/
import {... call} from 'redux-saga/effects'
import history from './history'
export default function* your_root_saga(){
  ...access history here or in your sub sagas...
  yield call([history, history.push], 'your_object_path')
}


/** index.js ****/
import history from './history'
import {Router, ...} from 'react-router-dom'
import your_root_saga from './sagas'
import {createSagaMiddleware} from 'redux-saga'

const sagaMiddleware = createSagaMiddleware()
...config_your_store_here...
sagaMiddleware.run(your_root_saga)


render( <Router history = {history}> ... </Router>
, document.getElementById('elementId'))
O answered 5/3, 2018 at 13:49 Comment(0)
J
3

You don't have react-router-redux set up fully (https://github.com/ReactTraining/react-router/tree/master/packages/react-router-redux)

You need

  • ConnectedRouter
  • Router reducer
  • Router middleware

Otherwise redux doesn't know what to do with the push action - no reducer or middleware knows that action, so they ignore it.

Joettejoey answered 16/1, 2018 at 23:25 Comment(1)
Alex thanks for your participation, I just updated the code (updated my post aswell) but its still doesnt work - can you have a look please?Tifanie
B
0

Looks like you forgot to add the routerReducer - Try this:

import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore, applyMiddleware, compose,
  combineReducers  // need this to add the routerReducer
} from 'redux'
import createSagaMiddleware from 'redux-saga'
import {
  ConnectedRouter,
  routerMiddleware,
  routerReducer // you need the router reducer
} from 'react-router-redux'
import createHistory from 'history/createBrowserHistory'

import App from './App.js'

import rootReducer from './reducers/rootReducer'
import setAuthorizationToken from './helpers/setAuthorizationToken'
import loginSaga from './sagas/loginSaga'
import registerSaga from './sagas/registerSaga'

const sagaMiddleware = createSagaMiddleware()

const history = createHistory()

const reduxRouterMiddleware = routerMiddleware(history)

const store = createStore(
  combineReducers({...rootReducer, router: routerReducer}),
  compose(
    applyMiddleware(sagaMiddleware, reduxRouterMiddleware),
    window.devToolsExtension ? window.devToolsExtension() : f => f
  )
)

sagaMiddleware.run(registerSaga)
sagaMiddleware.run(loginSaga)

if (window.localStorage.token) {
  setAuthorizationToken(window.localStorage.token)  
}

render(
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <App />
    </ConnectedRouter>
  </Provider>,
  document.getElementById('app')
)
Behring answered 18/1, 2018 at 4:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.