2020-09-10 19:25:52 +02:00
|
|
|
import { useQuery, DocumentNode, QueryHookOptions } from "@apollo/client";
|
2020-07-31 17:36:10 +02:00
|
|
|
import { useState, useEffect } from "react";
|
|
|
|
|
2020-09-10 19:25:52 +02:00
|
|
|
export function useGraphQLData<T, A = any, R = Record<string, any>>(q: DocumentNode, key: string, defaultValue: T, options: QueryHookOptions<A, R> = {}) {
|
2020-08-05 17:53:52 +02:00
|
|
|
const query = useQuery(q, options);
|
2020-07-31 17:36:10 +02:00
|
|
|
const [ data, setData ] = useState<T>(defaultValue);
|
|
|
|
useEffect(() => {
|
|
|
|
setData(query.data ? query.data[key] as T : defaultValue);
|
|
|
|
}, [query.loading, query.data]);
|
|
|
|
return { data, loading: query.loading, error: query.error };
|
|
|
|
}
|