@hollanditkzn

Как сделать выход пользователя?

Надо реализовать мне при выходе пользователя, но немного не могу понять как его реализовать
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import  { Provider } from 'react-redux';
import { createStore, combineReducers, compose, applyMiddleware } from 'redux';
import { Route, Switch, Redirect } from 'react-router';
import { BrowserRouter } from 'react-router-dom';
import thunk from 'redux-thunk';
import Helmet from './aplication';
import loginReducers from './reducer/loginDucks';
import Auth from "./AuthForm";
import Home from "./Home";

const rootReducer = combineReducers({
    login: loginReducers,
});

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(rootReducer, composeEnhancers(
    applyMiddleware(thunk)
));
sessionStorage.setItem('store', JSON.stringify(store));

ReactDOM.render(
        <div>
        <Helmet title='Авторизация'/>
        <Provider store={store}>
            <BrowserRouter>
                <Switch>
                    <Route exact path='/' render={()=>sessionStorage.getItem('store') ? <Redirect to='/index'/> : <Auth/>}/>
                    <Route path='/index' render={() => sessionStorage.getItem('store') ? <Home /> : <Redirect to='/'/>}/>
                </Switch>
            </BrowserRouter>
        </Provider>
        </div>,
    document.getElementById('content')
);
loginDucks
import axios from 'axios';

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

....

const loginLogout = data => ({
    type: LOGOUT
});

....
export const logout = () => async dispatch => {
    const res = await axios.get('/api/logout');
    if(!res.data) {
        sessionStorage.removeItem('store');
        dispatch(loginLogout());
    }
};

const initialState = {
    isLoading: false,
    isError: false,
    shouldRedirect: false,
    errorMessage: '',
    user: false,
};

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

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

router.js (это на node js)
router.get('/api/logout', async ctx => {
        ctx.logout();
    })

И в навигации я настриол выход, где пользователь может выйти из аккаунта
Header
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import {logout} from "../reducer/loginDucks";
import {connect} from "react-redux";

export default class Header extends Component{
    logout = e => {
        e.preventDefault();
        this.props.logout();
        return <Redirect to='/'/>;
    };
    render(){
        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="/logout" className="nav-link" onClick={this.logout}>Выйти</Link>
                    </li>
                </ul>
            </nav>
        );
    }
}

const mapStateToProps = state => ({
    isLoading: state.login.isLoading,
    isError: state.login.isError,
    shouldRedirect: state.login.shouldRedirect,
    errorMessage: state.login.errorMessage,
});

const mapDispatchToProps = {
    logout,
};

export default connect(mapStateToProps, mapDispatchToProps)(Header);
  • Вопрос задан
  • 456 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы