Infinite Scroll Example with React Apollo for GitHub GraphQL API

Dependency Packages

Component code

const RepoList = ({ data: { loading, error, search, loadMore } }) => {
if (loading) return <p>Loading...</p>;
if (error) return <p>Error, probably not logged in.</p>;
const {
nodes = [],
pageInfo: { hasNextPage } = {},
} = search || {};
return (
<InfiniteScroll
loadMore={loadMore}
hasMore={hasNextPage}
loader={<p>Loading...</p>}
>
<ul>
{nodes.map(item => (
<li key={item.url}><a href={item.url}>{item.name}</a></li>
))}
</ul>
</InfiniteScroll>
);
};

GraphQL query

const QUERY_REPOS = gql`
query ($q: String!, $end: String) {
search(first: 20, type: REPOSITORY, query: $q, after: $end) {
nodes {
... on Repository {
name
url
}
}
pageInfo {
endCursor
hasNextPage
}
}
}
`;

HoC by graphql

const withQuery = graphql(QUERY_REPOS, {
options: ({ q }) => ({ variables: { q } }),
props: ({ data }) => ({
data: {
...data,
loadMore: () => data.fetchMore({
variables: { end: data.search.pageInfo.endCursor },
updateQuery: (previousResult = {}, { fetchMoreResult = {} }) => {
const previousSearch = previousResult.search || {};
const currentSearch = fetchMoreResult.search || {};
const previousNodes = previousSearch.nodes || [];
const currentNodes = currentSearch.nodes || [];
return {
...previousResult,
search: {
...previousSearch,
nodes: [...previousNodes, ...currentNodes],
pageInfo: currentSearch.pageInfo,
},
};
},
}),
},
}),
});

Complete example

--

--

Freelance programmer. Open source enthusiast. Author of https://jotai.org, valtio, etc. https://contact.axlight.com https://discord.gg/MrQdmzd

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store