react-query with amplify graphql
Following previous post, you can use react-query to create a declarative API for Amazon's amplify graphql API interface:
Query #
import { useQuery } from "react-query";
// those are generated by Amplify
import { GetPostQuery } from "../API";
import { getPost } from "../graphql/queries";
const { data: post, isLoading, refetch } = useQuery(
["post", { id: params.id }],
async (_, { id }) => {
const result: any = await API.graphql(graphqlOperation(getPost, { id }));
return result.data as GetPostQuery;
}
);
Mutation #
import { useMutation } from "react-query";
// those are generated by Amplify
import { DeletePostMutationVariables } from "../API";
import { deletePost } from "../graphql/mutations";
const [deleteGalleryMutation, { isLoading: isDeleting }] = useMutation(
async (variables: DeletePostMutationVariables) =>
await API.graphql(graphqlOperation(deletePost, variables))
);