'use client' import { useQuery } from '@apollo/client/react' import { useCallback, useMemo, useRef } from 'react' import type { GraphQLResponse, UseApollo } from 'rntwsc/graphql/config' import { hk, normalizeGraphQLResponse } from 'rntwsc/graphql/config' import { clearHydrationErr, useApolloClient, useHydrationErr, } from 'rntwsc/graphql/store' import type { HydrationData, UseHydrationData } from 'rntwsc/hydration/config' import { dehydrate } from 'rntwsc/hydration/dehydrate' export const useFetchGraphQL = ({ url, query, variables, headers, }: UseApollo): UseHydrationData> => { const k = hk.key({ url, query, variables, headers, }) const client = useApolloClient(url) const r = useQuery(query, { client, variables, context: { headers, }, errorPolicy: 'all', fetchPolicy: 'cache-first', notifyOnNetworkStatusChange: true, }) const hydrationErr = useHydrationErr(k) const refetchRef = useRef(r.refetch) refetchRef.current = r.refetch const refetch = useCallback(() => { clearHydrationErr(k) return refetchRef.current(variables) }, [k, variables]) const v: HydrationData> = useMemo(() => { // only set data when apollo has result or there are graphql errors to surface const data: GraphQLResponse | undefined = r.data || hydrationErr?.errors ? normalizeGraphQLResponse({ data: r.data, errors: hydrationErr?.errors, }) : undefined return { data, error: hydrationErr?.error || (r.error && String(r.error)), } }, [hydrationErr, r.error, r.data]) return { ...dehydrate(k, v), loading: !hydrationErr && r.loading, refetch, } }