DEV Community

Cover image for Graphql mutations with github gql api : follow and unfollow a user
Dennis kinuthia
Dennis kinuthia

Posted on

2 1

Graphql mutations with github gql api : follow and unfollow a user

Graphql mutations

using the github graphql api with react-query

we'll use follow and unfollow user mutations
it takes in parmeter

input:FollowUserInput|UnfollowUserInput
Enter fullscreen mode Exit fullscreen mode

which has the fields

{userId:String! ,clientMutationId:String}
Enter fullscreen mode Exit fullscreen mode

so we'll be passing in the userId which we'll get from the user as id , we can ignore clientMutationId since it's not required

the mutations

import gql from "graphql-tag";

export const FOLLOWUSER = gql`
  mutation followUser($input: FollowUserInput!) {
    followUser(input: $input) {
      clientMutationId
    }
  }
`;

export const UNFOLLOWUSER = gql`
mutation unfollowUser($input:UnfollowUserInput!){
  unfollowUser(input:$input){
    clientMutationId
  }
}
`;
Enter fullscreen mode Exit fullscreen mode

custom usegQLmutatin

import { useMutation } from "react-query";
import { GraphQLClient } from "graphql-request";
import { DocumentNode } from "graphql";

export const useGQLmutation = (
  token: string,
  mutation: DocumentNode,
  config = {}
) => {
  const endpoint = "https://api.github.com/graphql";
  const headers = {
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
    },
  };
  const graphQLClient = new GraphQLClient(endpoint, headers);
  const fetchData = async (vars: any) => {
     return await graphQLClient.request(mutation,vars);
   };

   return useMutation((vars:any) => {return fetchData(vars)},config);

};

Enter fullscreen mode Exit fullscreen mode

usage in the project

const followMutation = useGQLmutation(token,FOLLOWUSER)
const unfollowMutation = useGQLmutation(token,UNFOLLOWUSER)
const [yes, setYes] = useState<any>(dev?.viewerIsFollowing);

const followThem = (their_id: string) => {
    setYes(true);
    // followUser(their_name, token);
    followMutation.mutate({input:{userId:their_id}})
  };
  const unfollowThem = (their_id: string) => {
    setYes(false);
    // unfollowUser(their_name, token);
    unfollowMutation.mutate({input:{userId:their_id}})
  };

Enter fullscreen mode Exit fullscreen mode

full project
live preview

API Trace View

Struggling with slow API calls? 👀

Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more