← Back
amplify aws graphql hooks react react-use

react-use and amplify graphql

[react-use] has a lot of hooks. One that caught my attention was useAsyncFn

useQuery #

You can use both to create a useQuery like hook for amplify graphql:

import { API, graphqlOperation } from "aws-amplify";
import { useEffect } from "react";
import { useAsyncFn } from "react-use";

export default function useQuery<T, V>(query: any, variables: V) {
const fetch = async (): Promise<any> =>
await API.graphql(graphqlOperation(query, variables));

const [state, refresh] = useAsyncFn(fetch);

useEffect(() => {
refresh();
}, [refresh]);

const { loading, error, value } = state;
const data = value ? (value.data as T) : undefined;
return { loading, error, data, refresh };
}

useMutation #

Or a mutation:

import { API, graphqlOperation } from "aws-amplify";
import { useAsyncFn } from "react-use";

export default function useMutation<T, V>(method: any) {
return useAsyncFn(
async (variables?: V): Promise<T> =>
API.graphql(graphqlOperation(method, variables)) as Promise<T>,
[method]
);
}

References #