Skip to content

Instantly share code, notes, and snippets.

@jmn
Created December 21, 2018 14:43
Show Gist options
  • Save jmn/6390b55e06c606ffa5e5241633f12eac to your computer and use it in GitHub Desktop.
Save jmn/6390b55e06c606ffa5e5241633f12eac to your computer and use it in GitHub Desktop.
Graphql with apollo react
import React from "react";
import { Query } from "react-apollo";
import gql from "graphql-tag";
const Q = gql`
query allPosts($cursor: String) {
allPosts(username: "jmn", first: 1, after: $cursor) {
edges {
node {
id
title
}
}
pageInfo {
startCursor
endCursor
}
}
}
`;
export const updateQuery = (previousResult, { fetchMoreResult }) => {
const newEdges = fetchMoreResult.allPosts.edges;
const pageInfo = fetchMoreResult.allPosts.pageInfo;
return {
allPosts: {
__typename: previousResult.allPosts.__typename,
edges: [...previousResult.allPosts.edges, ...newEdges],
pageInfo
}
};
};
const Posts = () => (
<Query query={Q}>
{({ loading, error, data, fetchMore }) => {
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
return (
<React.Fragment>
{data.allPosts.edges.map(({ node }) => (
<div key={node.id}>
<p>
<a href={node.id}>{`${node.title}`}</a>
</p>
</div>
))}
<button
onClick={() =>
fetchMore({
variables: { cursor: data.allPosts.pageInfo.endCursor },
updateQuery: updateQuery
})
}
>
Next
</button>
</React.Fragment>
);
}}
</Query>
);
export default Posts;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment