DEV Community

Ashish K Mishra
Ashish K Mishra

Posted on

2

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

Image descriptionTo 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay