bernabe9 / redux-react-session

:key: Simple Session API storage for Redux and React
https://bernabe9.github.io/redux-react-session/
147 stars 41 forks source link

How to access logout function out of Home.js #22

Closed palidaa closed 6 years ago

palidaa commented 6 years ago

I see your example home.js file and wondering how to call logout method.

bernabe9 commented 6 years ago

That's a question about React not an issue haha.

Anyways, I give you an example:

import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { logout } from '../actions/sessionActions';

class OtherComponent extends Component {
  constructor() {
    super()
    this.onClick = this.onClick.bind(this);
  }

  onClick() {
    this.props.logout();
  }

  render() {
    const { user, authenticated };

    return (
      <div>
        <h3>Welcome {user.email}</h3>
        <h5>{authenticated ? 'You are authenticated :)' : 'Error'}</h5>
        <button onClick={this.onClick}>
          LOGOUT
        </button>
      </div>
    );
  }
}

const { func, bool } = PropTypes;

OtherComponent.propTypes = {
  logout: func.isRequired,
  user: object.isRequired,
  authenticated: bool.isRequired
};

const mapState = (state) => ({
  user: state.session.user,
  authenticated: state.session.authenticated
});

const mapDispatch = (dispatch) => {
  logout = () => dispatch(logout())
};

export default connect(mapState, mapDispatch)(OtherComponent);

Hope it helps..