H
H
hollanditkzn2018-01-28 12:59:08
React
hollanditkzn, 2018-01-28 12:59:08

How to organize a logout for a user?

It is not possible to organize logout. It turns out that I need to click on the button and reload the page
. My implementation is the entire
Header.js code

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { Redirect } from 'react-router';
import { logout } from "../redux/login/loginActions";

class Header extends Component{
    logoutAccaunt = e => {
        e.preventDefault();
        this.props.logout();
    };
    render(){
        const { user } = this.props;
        if (user === null) return <Redirect to='/'/>;
        return(
            <nav className="navbar navbar-light bg-faded">
                <h1 className="navbar-brand">Holland</h1>
                <ul className="nav navbar-nav">
                    <li className="nav-item">
                        <Link to="/index" className='nav-link'>Главная страница<span className="sr-only">(current)</span></Link>
                    </li>
                    <li className="nav-item">
                        <Link to="#" className="nav-link">База знаний</Link>
                    </li>
                    <li className="nav-item">
                        <Link to="#" className="nav-link">Тренинги</Link>
                    </li>
                    <li className="nav-item">
                        <Link to="#" className="nav-link">Тестирование</Link>
                    </li>
                    <li className="nav-item">
                        <form className="form-inline">
                            <input type="text" placeholder="Поиск" className="form-control"/>
                            <button type="submit" className="btn btn-outline-success">Найти</button>
                        </form>
                    </li>
                    <li className="nav-item pull-xs-right">
                        <Link to="#" className="nav-link" onClick={this.logoutAccaunt}>Выйти</Link>
                    </li>
                </ul>
            </nav>
        );
    }
}

const mapStateToProps = state => {
    user: state.login.user
};

const mapDispatchToProps = {
    logout,
};

export default connect(mapStateToProps, mapDispatchToProps)(Header);

In loginActions.js
import axios from 'axios';

export const LOGIN_REQUEST = 'LOGIN_REQUEST',
  LOGIN_SUCCESS = 'LOGIN_SUCCESS',
  LOGIN_ERROR = 'LOGIN_ERROR',
  LOGOUT = 'LOGOUT';

export const loginSuccess = data => {
  const user = { id: data.id, login: data.login, name: data.name };

  sessionStorage.setItem('auth', JSON.stringify(user));

  return {
    type: LOGIN_SUCCESS,
    payload: user
  };
};

export const loginError = data => {
  sessionStorage.removeItem('auth');

  return {
    type: LOGIN_ERROR,
    payload: data
  };
};

export const logout = () => {
  sessionStorage.removeItem('auth');
  return {};
};

export const login = form => async dispatch => {
  try {
    const res = await axios.post('/api/user', form);

    if (!res.data || res.data === false) {
      dispatch(loginError('Неправильный логин или пароль'));
    } else {
      dispatch(loginSuccess(res.data));
    }
  } catch (e) {
    dispatch(loginError(e.response.data));
  }
};

loginReducer.js
import * as actions from './loginActions';

export const initialState = {
  isLoading: false,
  isError: false,
  shouldRedirect: false,
  errorMessage: '',
  user: localStorage.getItem('auth'),
};

export default (state = initialState, action) => {
  const { type, payload } = action;

  switch(type){
    case actions.LOGIN_REQUEST:
      return {
        ...state,
        isLoading: true,
        isError: false
      };
    case actions.LOGIN_SUCCESS:
      return {
        ...state,
        user: payload,
        isLoading: false,
        shouldRedirect: true
      };
    case actions.LOGIN_ERROR:
      return {
        ...state,
        errorMessage: payload,
        isLoading: false,
        isError: true,
      };
    case actions.LOGOUT:
      return {
        ...state,
        user: null
      };
    default:
      return state;
  }
}

And as a result I get this error in the console when I click
Header.js:47 Uncaught TypeError: Cannot read property 'user' of undefined
The above error occurred in the <Connect(Header)> component:
    in Connect(Header)
    in div
    in Unknown
    in WithHelmet
    in Route
    in AuthProvider (created by Connect(AuthProvider))
    in Connect(AuthProvider)
    in Router (created by BrowserRouter)
    in BrowserRouter
    in Provider
    in div
loginActions.js:43 Uncaught (in promise) TypeError: Cannot read property 'data' of undefined

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2018-01-28
@maxfarseer

export const logout = () => {
  sessionStorage.removeItem('auth');
  return {}; <-- забыли экшен свой { type: LOGOUT }
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question