How to write "Create mutations" in  React using Apollo Client

How to write "Create mutations" in React using Apollo Client

Table of contents

No heading

No headings in the article.

To create mutations with React Apollo Client, you'll need to follow a few steps.

Step 1: Set up your React project Create a new React project or navigate to your existing project directory. You can use create-react-app to quickly set up a new project by running the following command in your terminal:

npx create-react-app my-apollo-app

Step 2: Install required dependencies Navigate to your project directory and install the necessary dependencies by running the following command:

cd my-apollo-app
npm install @apollo/client graphql

This installs the Apollo Client and GraphQL packages required for performing mutations.

Step 3: Configure Apollo Client Create a new file called apolloClient.js in the src directory and add the following code to configure Apollo Client:

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

const client = new ApolloClient({
  uri: 'YOUR_GRAPHQL_API_ENDPOINT',
  cache: new InMemoryCache(),
});

export default client;

Replace 'YOUR_GRAPHQL_API_ENDPOINT' with the actual GraphQL API endpoint URL.

Step 4: Create a mutation component In your React project, create a new component for performing the mutation. For example, you can create a file called MutationComponent.js in the src directory. Here's an example of how the component may look:

import React from 'react';
import { gql, useMutation } from '@apollo/client';

const CREATE_POST = gql`
  mutation CreatePost($title: String!, $content: String!) {
    createPost(title: $title, content: $content) {
      id
      title
      content
    }
  }
`;

const MutationComponent = () => {
  const [title, setTitle] = React.useState('');
  const [content, setContent] = React.useState('');

  const [createPost, { loading, error }] = useMutation(CREATE_POST);

  const handleSubmit = (e) => {
    e.preventDefault();
    createPost({ variables: { title, content } })
      .then((response) => {
        console.log(response.data);
        // Handle successful mutation
      })
      .catch((error) => {
        console.error(error);
        // Handle error
      });
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          placeholder="Title"
        />
        <input
          type="text"
          value={content}
          onChange={(e) => setContent(e.target.value)}
          placeholder="Content"
        />
        <button type="submit" disabled={loading}>
          {loading ? 'Submitting...' : 'Submit'}
        </button>
      </form>
      {error && <p>Error: {error.message}</p>}
    </div>
  );
};

export default MutationComponent;

Step 5: Use the mutation component In your main App component or any other component where you want to use the mutation, import the MutationComponent and render it:

import React from 'react';
import MutationComponent from './MutationComponent';

const App = () => {
  return (
    <div>
      <MutationComponent />
    </div>
  );
};

export default App;

That's it! You have now set up a mutation component using React Apollo Client. When you submit the form, it will trigger the mutation and send the data to the GraphQL API endpoint specified in the apolloClient.js configuration file.

Did you find this article valuable?

Support Ashish K Mishra by becoming a sponsor. Any amount is appreciated!