Last active
March 20, 2017 20:33
-
-
Save matthewlehner/6b64a0087b871549520bf6be83ae1d9d to your computer and use it in GitHub Desktop.
Apollo with React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import { render } from "react-dom"; | |
import { ApolloClient, ApolloProvider } from "react-apollo"; | |
import UserProfile from "user-profile" | |
const client = new ApolloClient(); | |
const reactRoot = document.getElementById("react-root"); | |
// Wrap components at the top level with ApolloProvider - this allows us | |
// to hook into its store locally. | |
// | |
// Also, statically passing a `userId` prop with the value of 1 to the | |
// UserProfile component. | |
render( | |
<ApolloProvider client={client}> | |
<UserProfile userId={1} /> | |
</ApolloProvider>, | |
reactRoot | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from "react"; | |
import { gql, graphql } from "react-apollo"; | |
class UserProfile extends Component { | |
render() { | |
// These props are coming from the Apollo store. Further down, | |
// the component is wrapped in a 'higher order' component that adds | |
// them to the current view. | |
const { data: { user, loading } } = this.props; | |
if (loading) { return <div>Loading…</div>; } | |
return( | |
<div> | |
<h1>{{user.name}}</h1> | |
<p>The user is ID: {{user.id}}</p> | |
</div> | |
); | |
} | |
} | |
const UserProfileForLayout = gql` | |
query UserProfileForLayout($id: ID!) { | |
user(id: $id) { | |
name | |
} | |
} | |
`; | |
const WrapComponentWithQuery = graphql( | |
UserProfileForLayout, | |
{ | |
// Here, we set the variables that will be used by the query. The | |
// function receives `props` as an argument, and we destructure to retrieve | |
// the `userId` prop that's set statically in index.jsx | |
options: ({userId}) => ({ variables: { id: userID } }) | |
} | |
); | |
export default WrapComponentWithQuery(UserProfile); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment