How to handle logout route in Redux?

Gajus picture Gajus · Jan 11, 2016 · Viewed 31.4k times · Source

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.

Answer

Diego V picture Diego V · Jul 8, 2016

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))