Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
NullVoxPopuli opened this issue Dec 20, 2017 · 1 comment
Closed

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

NullVoxPopuli opened this issue Dec 20, 2017 · 1 comment

Comments

@NullVoxPopuli
Copy link

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 ?

@NullVoxPopuli
Copy link
Author

NullVoxPopuli commented Jan 5, 2018

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>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant