score:0

Accepted answer
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import LocalStorageManager from 'utils/LocalStorageManager';
import { selectCurrentUser, selectHasInitialized } from 'client/selectors/authSelectors';
import { setAccessToken, getProfile } from 'shared/api';
import { setHasInitialized, signIn } from 'modules/auth/actions.js';
import SinglePageCard from 'components/layout/SinglePageCard';

const mapStateToProps = (state) => {
  return {
    currentUser: selectCurrentUser(state),
    hasInitialized: selectHasInitialized(state),
  };
};

export default (WrappedComponent) => {
  class Layout extends Component {
    componentWillMount() {
      const accessToken = LocalStorageManager.getAccessToken();
      if (!accessToken) {
        this.props.setHasInitialized();
        return;
      }

      setAccessToken(accessToken);
      getProfile().then((response) => {
        console.log(response);
        const { user } = response.data.data;
        this.props.signIn(user);
      }).catch((error) => {
        console.log(error);
        this.props.setHasInitialized();
      });
    }

    render() {
      const { currentUser, hasInitialized, ...rest } = this.props;
      if (!hasInitialized) {
        return (
          <SinglePageCard>
            <div>Initializing...</div>
          </SinglePageCard>
        );
      }

      return (
        <WrappedComponent {...rest} />
      );
    }
  }
  return withRouter(connect(mapStateToProps, { setHasInitialized, signIn })(Layout));
};

Related Query

More Query from same tag