In the below examples, I Implementing client-side
logout with React Router and there are two things I had to do to make this
work:
1. Clear
the token in localStorage
2. Push
the url for the homepage onto the history prop
Example
1,
import React, { Component } from 'react'
import { baseUrl } from '../assets/js/helpers';
export default class Logout extends Component {
logout = () => {
window.localStorage.clear();
window.location.href = baseUrl + "login";
}
render() {
return (
<button onClick={this.logout}>Logout</button>
)
}
}
Example
2,
import React from 'react'
import { baseUrl } from '../assets/js/helpers';
export default () => {
const logout = () => {
window.localStorage.clear();
window.location.href = baseUrl + "login";
}
return (
<button onClick={logout}>Logout</button>
)
}
Example
3,
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))
You should check out the docs.