cantierecreativo/redux-bees

What's the recommended way to get the current user?

Closed this issue · 1 comments

esp if the token is stored in local storage.
maybe an auth token needs to be loaded into the store on app boot, and then get that out of the state to trigger a call to users/current-user ?

decided to do it this way:

import {Component} from 'react'
import {connect} from 'react-redux'
import {branch} from 'recompose'
import _ from 'lodash';
import { withRouter } from 'react-router'

import Loader from 'components/Loader'
import {FetchError} from 'components/Errors'

import {
  query,
  PLURAL as USERS,
  default as usersAPI
} from 'api/users'

@withRouter
@connect(state => ({ auth: state.auth }))
@branch(
  ({ auth }) => auth.token,
  query(USERS, usersAPI.currentUser)
)
export default class FetchCurrentUser extends Component {
  render() {
    const {
      children, status, [USERS]: result
    } = this.props;

    if (_.isEmpty(status)) {
      return (
        <div data-test="token-not-present" className='d-flex flex-grow'>
          {children}
        </div>
      );
    }

    const  { [USERS]: { isLoading, hasFailed, error } } = status;

    if (result) {
      return (<div>{children}</div>);
    }

    return (
      <div className='d-flex flex-grow justify-content-center align-items-center'>
        { hasFailed && <FetchError error={error} /> }

        { isLoading && <Loader />}
      </div>
    );
  }
}
<FetchCurrentUser>
  routes that require current user
</FetchCurrentUser>