GraphQL
Beginner
1 min read
Apollo Client: Queries and Mutations
Example
// npm install @apollo/client graphql
import { ApolloClient, InMemoryCache, ApolloProvider, gql, useQuery, useMutation } from '@apollo/client';
// 1. Create client
const client = new ApolloClient({
uri: 'https://api.example.com/graphql',
cache: new InMemoryCache(),
headers: { Authorization: `Bearer ${localStorage.getItem('token')}` },
});
// 2. Wrap app
function App() {
return <ApolloProvider client={client}><Posts /></ApolloProvider>;
}
// 3. Query hook
const GET_POSTS = gql`
query GetPosts($limit: Int!) {
posts(first: $limit) {
edges { node { id title author { name } } }
}
}
`;
function Posts() {
const { loading, error, data, refetch } = useQuery(GET_POSTS, {
variables: { limit: 10 },
pollInterval: 30000, // auto-refresh every 30s
});
if (loading) return <p>Loading…</p>;
if (error) return <p>Error: {error.message}</p>;
return data.posts.edges.map(({ node }) => <div key={node.id}>{node.title}</div>);
}
// 4. Mutation hook
const CREATE_POST = gql`
mutation CreatePost($input: CreatePostInput!) {
createPost(input: $input) { id title }
}
`;
function NewPostForm() {
const [createPost, { loading }] = useMutation(CREATE_POST, {
refetchQueries: [{ query: GET_POSTS, variables: { limit: 10 } }],
});
const submit = (title) => createPost({ variables: { input: { title, body: '...' } } });
return <button onClick={() => submit('New Post')} disabled={loading}>Add</button>;
}
Related Resources
GraphQL Reference
Complete tag & property list
GraphQL How-To Guides
Step-by-step practical guides
GraphQL Exercises
Practice what you've learned
More in GraphQL