🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

GraphQL with React

React DatađŸŸĸ Free Lesson

Advertisement

GraphQL with React

Apollo Client, queries, mutations, subscriptions, and caching strategies.

Overview

GraphQL provides a flexible query language for APIs with Apollo Client as the React implementation.

Key Concepts

  • Apollo Client — GraphQL client with React hooks
  • Queries — Fetch data with useQuery
  • Mutations — Modify data with useMutation
  • Subscriptions — Real-time updates with useSubscription
  • Cache — Normalized cache with automatic updates

Code Examples

import { ApolloClient, InMemoryCache, gql, useQuery, useMutation } from '@apollo/client';

const GET_POSTS = gql`
  query GetPosts($limit: Int) {
    posts(limit: $limit) {
      id
      title
      author { name }
    }
  }
`;

const CREATE_POST = gql`
  mutation CreatePost($input: PostInput!) {
    createPost(input: $input) {
      id
      title
    }
  }
`;

function PostList() {
  const { loading, error, data } = useQuery(GET_POSTS, { variables: { limit: 10 } });

  if (loading) return <Spinner />;
  if (error) return <ErrorMessage error={error} />;

  return (
    <ul>
      {data.posts.map(post => (
        <li key={post.id}>
          <h3>{post.title}</h3>
          <p>By {post.author.name}</p>
        </li>
      ))}
    </ul>
  );
}

function CreatePostForm() {
  const [createPost, { loading }] = useMutation(CREATE_POST, {
    refetchQueries: [{ query: GET_POSTS }],
  });

  const handleSubmit = async (e) => {
    e.preventDefault();
    await createPost({ variables: { input: { title: e.target.title.value } } });
    e.target.reset();
  };

  return (
    <form onSubmit={handleSubmit}>
      <input name="title" required />
      <button type="submit" disabled={loading}>Create</button>
    </form>
  );
}

Practice

Build a real-time comment system with GraphQL subscriptions.

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Related Tutorials

Content with similar topics across other courses

Continue Learning

Suggested next tutorials based on this topic

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement