user2999287
user2999287

Reputation:

React Redux with redux-observable use the router to navigate to a different page after async action complete

I am using redux-observable and this is my login epic:

const login = ( action$ ) => {
    return action$.ofType(SessionActions.LOGIN_USER)
      .flatMap(( {payload} ) => {
        return sessionService.login(payload)
          .do(payload => {
            sessionService.setSession(payload));
          // Here I want to redirect the user back to his last location
          }).map(result => ({
            type: SessionActions.LOGIN_SUCCESS,
            payload: result
          }));
      });
  }

But how I am redirecting the user to a different page after the login action success.

What is the redux way to do this?

Upvotes: 4

Views: 5611

Answers (2)

robinvdvleuten
robinvdvleuten

Reputation: 1514

If you use redux-observable with react-router-redux, you can do any redirections within your epics:

import { ajax } from 'rxjs/observable/dom/ajax';
import { push } from 'react-router-redux';
import NProgress from 'nprogress';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';

export default function login(action$) {
  return action$.ofType('LOGIN_USER')
    .do(() => NProgress.start())
    .mergeMap(payload => (
       // Call your login service here, please note that it must be an observable to continue in your epic chain.
       Observable.fromPromise(sessionService.setSession(payload))
         // This is the redirect you're looking for, it's now became an action thanks to react-router-redux :)
         .mapTo(push({ url: '/' }))
         .do(() => NProgress.done())
  ));
}

I have even added a progress indicator for the bonus points :) It's constructed with help from redux-observable's own navigation example

Upvotes: 10

Sour Code
Sour Code

Reputation: 46

I'm totally new to react/redux, but I face the same problem as you, so I create a small APP with a login page.

// On your Login.JS you could implement the component lifecycle

componentWillReceiveProps(nextProps) {
    if (nextProps.isAuthenticated){
        this.context.router.push({pathname:'/'});
    }
}

So, when your 'action' send to the 'reducer' the type: LOGIN_SUCCESS your going to change the corresponding state and when your component 'receive props' your going to check and redirect. I hope this small example help you.

Upvotes: 3

Related Questions