Skip to content

Instantly share code, notes, and snippets.

@tigawanna
Created September 3, 2022 10:47
Show Gist options
  • Save tigawanna/6c83d65f4fcc783f8ef2a8b69e9ff4bf to your computer and use it in GitHub Desktop.
Save tigawanna/6c83d65f4fcc783f8ef2a8b69e9ff4bf to your computer and use it in GitHub Desktop.
how to follow a user in github graphql with react query

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

which has the fields

{userId:String! ,clientMutationId:String}

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
  }
}
`;

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);

};

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}})
  };

full project live preview

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment