DEV Community

Max Frolov
Max Frolov

Posted on • Edited on

React Hook around Apollo GraphQL mutation

Here is an example of custom hook around Apollo mutation, which includes error and loading states to keep UX in sync with what is happening.
BTW you can check React Hook around Apollo GraphQL query here.

import * as RH from "@apollo/react-hooks";
import gql from "graphql-tag";

// activate user query
export const ACTIVATE_USER_MUTATION = gql`
  mutation ActivateUserMutation($input: ActivateUserInput) {
    activateUser(input: $input) {
      firstName
      lastName
      online
      id
    }
  }
`;

// entity mutation hook
export const useActivateUserMutation = () => {
  // gql hook
  const [activateUser, { data, loading, error }] = RH.useMutation(ACTIVATE_USER_MUTATION);

  const handleActivateUser = async (variables) => {
    try {
      const {
        data: {
          activateUser: { id }
        }
      } = await activateUser({ variables });
      // call fn to show some success box in the interface

      return id;
    } catch (error) {
      // parse error here
      console.log(error.graphQLErrors)
    }
  };

  return {
    activateUser: handleActivateUser, // mutation handler
    result: data, // mutation result
    isLoading: loading, // loading state
    error // mutation error state
  };
};

More tips and best practices on my twitter.

Feedback is appreciated. Cheers!

Top comments (6)

Collapse
 
shepeliev profile image
Dmytro Shepeliev

Hi Max!

Thanks for sharing your experience! May you please describe what are benefits using you approach versus graphql HOC?

Collapse
 
max_frolov_ profile image
Max Frolov

This approach allows you to:
1) keep things reusable
2) keep things in one place

Collapse
 
thisdotmedia_staff profile image
This Dot Media

Nice!

Collapse
 
alucardu profile image
Peter Boomsma

Just getting into Apollo and React so this might be a silly question. But this very much like a functional component that has a Apollo hook in it with relevant return values. How is this a custom hook compared to a functional component?

Collapse
 
lomse profile image
Sélom Amouzou

Looks great!

Collapse
 
jegardner profile image
Jack Gardner