How to handle logout route in Redux?

I want to define a URL that can be used to log out (submit an action that logs out). I did not find examples showing how to implement the route sending the event.

+9
redux react-router react-router-redux
source share
3 answers

Define the 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 sends the action to 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 sends two actions:

  • To destroy a user session.
  • To redirect the user to IndexRoute .
 this.props.dispatch(authenticationActionCreator.logout()); this.props.dispatch(pushPath('/')); 
+9
source share

Here is a more relevant implementation for this page /logout :

 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)) 
+9
source share

Here is the latest implementation of the /logout page:

 import React, { Component } from "react"; import PropTypes from "prop-types"; import { connect } from "react-redux"; import { Redirect } from "react-router-dom"; import * as authActionCreators from "../actions/auth"; class LogoutPage extends Component { static propTypes = { dispatch: PropTypes.func.isRequired }; componentWillMount() { this.props.dispatch(authActionCreators.logout()); } render() { return ( <Redirect to="/" /> ); } } export default connect()(LogoutPage); 

Works for:

 "react": "^15.6.1", "react-dom": "^15.6.1", "react-redux": "^5.0.6", "react-router-dom": "^4.2.2", "prop-types": "^15.5.10", 
+5
source share

All Articles