Skip to content

Instantly share code, notes, and snippets.

@matthewlehner
Last active March 20, 2017 20:33
Show Gist options
  • Save matthewlehner/6b64a0087b871549520bf6be83ae1d9d to your computer and use it in GitHub Desktop.
Save matthewlehner/6b64a0087b871549520bf6be83ae1d9d to your computer and use it in GitHub Desktop.
Apollo with React
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
);
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