Содержание
Мутации Graphql
использование github graphql api с react-query
мы будем использовать мутации следовать и не следовать за пользователем
это займет в парметре
input:FollowUserInput|UnfollowUserInput
в котором есть поля
{userId:String! ,clientMutationId:String}
поэтому мы будем передавать userId, который мы получим от пользователя как id, мы можем игнорировать clientMutationId, так как он не требуется
мутации
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
}
}
`;
пользовательский 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);
};
использование в проекте
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}})
};
полный проект
живой просмотр