Skip to content

Instantly share code, notes, and snippets.

@arunoda
Last active November 25, 2015 15:39
Show Gist options
  • Save arunoda/9d3cec6b5019b6c3ae74 to your computer and use it in GitHub Desktop.
Save arunoda/9d3cec6b5019b6c3ae74 to your computer and use it in GitHub Desktop.
This is a demo of how to write a simple app with our GraphQL Cache.
const GraphQLCache = require('graphql-cache');
const HttpTransport = require('graphql-cache-http-transport');
const React = require('react');
const ReactDOM = require('react-dom');
const Cache = new GraphQLCache({
transport: new HttpTransport('/graphql');
});
// Create the fragment where we can use later on
const postFragment = Cache.defineFragment(() => (`
fragment abc on Post {
id,
title,
summary,
votes
}
`));
// Define a query and use the fragment inside it
const recentPosts = Cache.defineQuery(args => (`
latestPosts(count: ${args.count || 10}) {
${postFragment.include()}
}
`));
// Define the mutation and decide what to do in when we get the data
// and when running the simulation for optimistic updates
const mutationUpvote = Cache.defineMutation(
// the mutation query that will send to the server
args => (
`upvote(id: "$args.id") {
votes
}
`
),
// what to do when data arrives
(args, err, postFromServer) => {
// This will re-render the whole UI again
if(err) {
alert(err.message);
// It's safe to simply return.
// All the changes has been done in the simulation
// will be reverted automatically.
return;
}
this.posts.merge(args.id, postFromServer);
},
// simulation for optimistic updates
args => {
const post = _.clone(args);
post.inSimulation = true;
post.votes++;
// This will be replaced when the data comes from the server and applied
// the above function
this.posts.merge(args.id, post);
}
)
// Simple React component which accpets our GraphQL data from the props
const PostsComponent extend React.Component {
constructor({data, ready}) {
this.postList = (ready)? data : [];
this.renderPost = this.renderPost.bind(this);
super();
}
getClasses(post) {
return (post.inSimulation)? 'post simulation': 'post';
}
upvote(post) {
mutationUpvote(post);
}
renderPost(post) {
return (
<div key={post.id} className={this.getClasses(post)}>
<h2>[{post.votes}] {post.title}</h2>
<button onClick={this.upvote.bind(this, post)}>Upvote</button>
<p clsssName='summary'>{post.summary}</p>
</div>
);
}
render() {
return (
<div className='postList'>
{this.postList.map(this.renderPost)}
</div>
);
}
}
// Wrap our PostsComponent with the data we got from the GraphQL endpoint
const PostsComponentWithData = recentPosts(10)
.wrapComponent(PostsComponent);
// Render the wrapped component wherever we want
ReactDOM.render(<PostsComponentWithData />, document.body);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment