установка элемента в localforage регистрирует пользователя - PullRequest
0 голосов
/ 13 марта 2019

Я работаю в ReactJS, используя localforage для извлечения пользователя, вошедшего в данный момент. В веб-приложении есть несколько мест, где я пытаюсь обновить информацию о текущем пользователе, но я хочу, чтобы оно обновлялось у текущего пользователя и сохранялось в localforage как Что ж. Если я пытаюсь установить currentuser, он выходит из системы. Что я тут не так делаю?

Вот индексный файл моего приложения:

/**
 *
 * App.js
 *
 */

import React from 'react';
import { Switch, Route, Redirect } from 'react-router-dom';
import localforage from 'localforage';
import { get, isEmpty, set } from 'lodash';
import HomePage from '../../containers/HomePage/Loadable';
import Signup from '../../containers/Signup/Loadable';
import Login from '../../containers/Login/Loadable';
import signupConfirmation from '../../containers/signupConfirmation/Loadable';
import HostLandingPage from '../../containers/HostLandingPage/Loadable';
import CustomerLandingPage from '../../containers/CustomerLandingPage/Loadable';
import HostSignup from '../../containers/HostSignup/Loadable';
import CustomerSignup from '../../containers/CustomerSignup/Loadable';
import MainContainer from '../../containers/MainContainer/Loadable';
import NotFoundPage from '../../containers/NotFoundPage/Loadable';
import ForgotPassword from '../../containers/ForgotPassword/Loadable';
import CheckAccount from '../../containers/CheckAccount/Loadable';
import ResetPassword from '../../containers/ResetPassword/Loadable';
import HostRoutes from './HostRoutes';
import CustomerRoutes from './CustomerRoutes';
import store from '../../reduxApp/store';

export default class App extends React.Component { // eslint-disable-line react/prefer-stateless-function
  constructor(props) {
    super(props);
    this.state = { userLoaded: false };
  }

  componentWillMount = async () => {
    this.setState({
      userLoaded: true,
      user: await localforage.getItem('currentUser'),
    });
  }

  // get user from either local storage or from redux store
  getAccessToken = () => get(this.getCurrentUser(), 'accessToken');

  getCurrentUser = () => {
    const { user: userInState } = this.state;
    const userInRedux = get(store.getState().get('auth'), 'currentUser');
    if (!isEmpty(userInRedux)) {
      return userInRedux;
    }
    return userInState;
  }

  getUserRoutes = (userRole) => {
    if (userRole === 'Customer') {
      return <CustomerRoutes requireAuth={this.requireAuth} />;
    } else if (userRole === 'Host') {
      return <HostRoutes requireAuth={this.requireAuth} />;
    }
    return <Redirect to="/login" />;
  }

  requireAuth = (ComponentToRender) => () =>
    this.getAccessToken()
      ? (
        <MainContainer style={{ height: '100%' }}>
          <ComponentToRender />
        </MainContainer>
      )
      : <Redirect to="/login" />


  render() {
    // a hack to wait for the user to be loaded from localStorage
    const { requireAuth } = this;
    const userRole = get(this.getCurrentUser(), 'type');
    set(this.getCurrentUser(), 'type', null);
    if (userRole === 'Host' || userRole === 'Customer') {
      return (
        <div style={{ height: '100%' }}>
          <Switch>
            { this.getUserRoutes(userRole) }
            <Route component={NotFoundPage} />
          </Switch>
        </div>
      );
    }
    return (
      <div style={{ height: '100%' }}>
        <Switch>
          <Route exact path="/" component={HomePage} />
          <Route exact path="/signup" component={Signup} />
          <Route exact path="/login" component={Login} />
          <Route exact path="/confirmation" component={signupConfirmation} />
          <Route exact path="/host" component={HostLandingPage} />
          <Route exact path="/customer" component={CustomerLandingPage} />
          <Route exact path="/host/signup" component={HostSignup} />
          <Route exact path="/customer/signup" component={CustomerSignup} />
          <Route exact path="/forgot/password" component={ForgotPassword} />
          <Route exact path="/check/account" component={CheckAccount} />
          <Route exact path="/password/edit" component={ResetPassword} />
        </Switch>
      </div>
    );
  }
}
...