Skip to content

Instantly share code, notes, and snippets.

@vladinator1000
Last active May 23, 2019 14:37
Show Gist options
  • Save vladinator1000/2b8a77b7b3f42e9b9f2aa4d2638ad0a1 to your computer and use it in GitHub Desktop.
Save vladinator1000/2b8a77b7b3f42e9b9f2aa4d2638ad0a1 to your computer and use it in GitHub Desktop.
Apollo client example
import React, { useState } from 'react'
import { gql } from 'graphql-tag'
import { QueryResult } from '@apollo/react-common'
import { useQuery } from '@apollo/react-hooks'
import * as GeneratedTypes from "./__generated__/GetSubreddit"
import Picker from './components/Picker'
// the GraphQL query, can also be imported from a file
const GET_SUBREDDIT = gql`
query GetSubreddit($name: String!) {
subreddit(name: $name) {
posts {
title
}
}
}
`;
function App() {
const [selectedSubreddit, setSelectedSubreddit] = useState("reactjs")
const {
data,
loading,
error,
refetch,
networkStatus,
// Direct access to the GraphQL client, can be very powerful
client
}: QueryResult<
GeneratedTypes.GetSubreddit,
GeneratedTypes.GetSubredditVariables
> = useQuery(GET_SUBREDDIT, {
variables: { name: selectedSubreddit },
notifyOnNetworkStatusChange: true
});
const refetching = networkStatus === 4;
if (loading && !refetching) {
return <h2>Loading...</h2>;
}
if (error) {
return <h2>${error}</h2>;
}
return (
<div>
<Picker
value={selectedSubreddit}
onChange={setSelectedSubreddit}
options={["reactjs", "frontend"]}
/>
<ul style={{ opacity: refetching ? 0.5 : 1 }}>
{data &&
data.subreddit &&
subreddit.posts.map(post => <li>{post.title}</li>)}
</ul>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment