Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle logout route in Redux?

I want to define a URL that could be used to logout the user (dispatch an action that would logout the user). I have not found examples showing how to implement a route dispatching an event.

like image 311
Gajus Avatar asked Jan 11 '16 11:01

Gajus


2 Answers

Here is a more current implementation for such /logout page:

import { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import { withRouter } from 'react-router'
import * as authActionCreators from '../actions/auth'

class LogoutPage extends Component {

  componentWillMount() {
    this.props.dispatch(authActionCreators.logout())
    this.props.router.replace('/')
  }

  render() {
    return null
  }
}
LogoutPage.propTypes = {
  dispatch: PropTypes.func.isRequired,
  router: PropTypes.object.isRequired
}

export default withRouter(connect()(LogoutPage))
like image 145
Diego V Avatar answered Nov 08 '22 21:11

Diego V


Define a route /authentication/logout:

import React from 'react';
import {
    Route,
    IndexRoute
} from 'react-router';
import {
    HomeView,
    LoginView,
    LogoutView
} from './../views';

export default <Route path='/'>
    <IndexRoute component={HomeView} />

    <Route path='/authentication/logout'component={LogoutView} />
    <Route path='/authentication/login' component={LoginView} />
</Route>;

Create a LogoutView that dispatches an action upon componentWillMount:

import React from 'react';
import {
    authenticationActionCreator
} from './../actionCreators';
import {
    connect
} from 'react-redux';
import {
    pushPath
} from 'redux-simple-router';

let LogoutView;

LogoutView = class extends React.Component {
    componentWillMount () {
        this.props.dispatch(authenticationActionCreator.logout());
        this.props.dispatch(pushPath('/'));
    }

    render () {
        return null;
    }
};

export default connect()(LogoutView);

The componentWillMount callback dispatches two actions:

  • To destroy user session.
  • To redirect user to the IndexRoute.
this.props.dispatch(authenticationActionCreator.logout());
this.props.dispatch(pushPath('/'));
like image 36
Gajus Avatar answered Nov 08 '22 21:11

Gajus