Skip to content

Instantly share code, notes, and snippets.

@kdipaolo
Created May 28, 2018 14:23
Show Gist options
  • Save kdipaolo/1cbd8b1cc5c4ed02c6a8c851581fb9c9 to your computer and use it in GitHub Desktop.
Save kdipaolo/1cbd8b1cc5c4ed02c6a8c851581fb9c9 to your computer and use it in GitHub Desktop.
// User Render Porop
// A user can wrap this <GetUser /> component around any other component and have access to the current user.
// This strategy helps create modularity and avoids passing the user info down via props which can pollute the code base
// Usage
<GetUser>
{user =>
user.subscription === 'paid' && (
<GoBoss to="/proposal-preview/go-boss">
<span>Create unlimited proposals only $10 a month!</span>
<Button inline>Go Boss</Button>
</GoBoss>
)
}
</GetUser>
// implementation
import React from 'react'
import { Query } from 'react-apollo'
import gql from 'graphql-tag'
import LoadingOverlay from './LoadingOverlay'
const USERINFO = gql`
query($id: ID!) {
User(id: $id) {
id
name
email
admin
subscription
}
}
`
const LOGGED_IN_USER = gql`
query {
loggedInUser {
id
}
}
`
export default ({ children }) => {
return (
<Query query={LOGGED_IN_USER} fetchPolicy="cache-only">
{({ loading, error, data }) => {
if (loading || error) return null
if (data.loggedInUser) {
return (
<Query
query={USERINFO}
variables={{ id: data.loggedInUser && data.loggedInUser.id }}
>
{({ loading, error, data }) => {
if (loading || error) return null
return children(data && data.User)
}}
</Query>
)
} else {
return children()
}
}}
</Query>
)
}
export const IsLoggedIn = ({ children }) => {
return (
<Query query={LOGGED_IN_USER}>
{({ loading, error, data }) => {
if (loading) {
return <LoadingOverlay />
}
const loggedInId = data.loggedInUser ? data.loggedInUser.id : null
if (loading || error) return null
return children(loggedInId)
}}
</Query>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment