Queries, Mutations, and Subscriptions in React JS
Introduction
In this tutorial, we will cover how to use Apollo Client with React to work with GraphQL operations: Queries, Mutations, and Subscriptions.
Step 1: Setting Up Apollo Client in React
Before diving into Queries, Mutations, and Subscriptions, make sure you have Apollo Client set up in your React application. Follow the steps below:
Install Apollo Client and GraphQL:
npm install @apollo/client graphql
Set up Apollo Client and wrap your application with the ApolloProvider (see the previous tutorial on Setting up Apollo Client in React).
Step 2: Setting Up Apollo Client
Configure Apollo Client as follows:
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';
// Create an instance of ApolloClient
const client = new ApolloClient({
uri: 'http://localhost:4000/', // Replace with your GraphQL API endpoint
cache: new InMemoryCache(),
});
export default client;
Step 3: Queries in React
Queries are used to fetch data from a GraphQL server. Let's create a simple query to fetch a list of users from a server.
First, define the GraphQL query in a component using Apollo's useQuery
hook.
import React from 'react';
import { useQuery, gql } from '@apollo/client';
// Define the GraphQL query
const GET_USERS = gql`
query GetUsers {
users {
id
name
}
}
`;
const UsersList = () => {
const { loading, error, data } = useQuery(GET_USERS);
if (loading) return Loading...
;
if (error) return Error: {error.message}
;
return (
{data.users.map((user) => (
- {user.name}
))}
);
};
export default UsersList;
In the example above, we define a GET_USERS
query that fetches users from the GraphQL API. The useQuery
hook automatically handles loading, error, and data states, and we display the user names in a list.
Step 4: Mutations in React
Mutations are used to modify data on the server. For example, adding a new user. Let's create a mutation for adding a new user.
First, define the mutation and use it in a component using Apollo's useMutation
hook.
import React, { useState } from 'react';
import { useMutation, gql } from '@apollo/client';
// Define the GraphQL mutation
const ADD_USER = gql`
mutation AddUser($name: String!) {
addUser(name: $name) {
id
name
}
}
`;
const AddUserForm = () => {
const [name, setName] = useState('');
const [addUser] = useMutation(ADD_USER);
const handleSubmit = async (e) => {
e.preventDefault();
try {
await addUser({ variables: { name } });
setName('');
} catch (error) {
console.error("Error adding user:", error);
}
};
return (
);
};
export default AddUserForm;
In the code above:
ADD_USER
: The mutation for adding a user. It accepts aname
argument and returns theid
andname
of the new user.useMutation
: The hook used to execute the mutation. Thevariables
are passed when the mutation is triggered.handleSubmit
: The function that submits the form and calls the mutation when the form is submitted.
Step 5: Subscriptions in React
Subscriptions allow you to listen for real-time updates from the server. For example, let's create a subscription to receive updates whenever a new user is added to the server.
Define the subscription and use it in a component with Apollo's useSubscription
hook:
import React from 'react';
import { useSubscription, gql } from '@apollo/client';
// Define the GraphQL subscription
const USER_ADDED = gql`
subscription OnUserAdded {
userAdded {
id
name
}
}
`;
const NewUserNotification = () => {
const { data, loading, error } = useSubscription(USER_ADDED);
if (loading) return Waiting for new users...
;
if (error) return Error: {error.message}
;
return New user added: {data.userAdded.name}
;
};
export default NewUserNotification;
In this code:
USER_ADDED
: The subscription that listens for new users added to the server.useSubscription
: The hook used to subscribe to real-time data. It works similarly touseQuery
, but automatically updates the UI with new data as it's received.
Step 6: Running Your App
After setting up queries, mutations, and subscriptions, you can run your React app as usual:
npm start
Your app should now support querying, mutating, and subscribing to real-time events using GraphQL and Apollo Client.
Conclusion
In this tutorial, we learned how to use Apollo Client in React for:
- Queries: Fetching data from a GraphQL server using the
useQuery
hook. - Mutations: Modifying data on the server using the
useMutation
hook. - Subscriptions: Listening for real-time updates using the
useSubscription
hook.
By using these GraphQL operations, you can effectively manage data flow in your React applications and handle real-time updates, creating a more dynamic and interactive experience.