UNPKG

@gqty/react

Version:

The No-GraphQL Client for React

55 lines (52 loc) 1.79 kB
import { useRerender } from '@react-hookz/web'; import * as React from 'react'; function createGraphqlHOC({ createResolver, subscribeLegacySelections }, { defaults: { suspense: defaultSuspense, retry } }) { const graphql = function graphql2(component, { onError, operationName, staleWhileRevalidate, suspense = defaultSuspense } = {}) { const withGraphQL = function WithGraphQL(props) { const { accessor: { query, mutation, subscription }, context, resolve } = createResolver({ operationName, retryPolicy: retry }); const unsubscribe = subscribeLegacySelections((selection, cache) => { context.select(selection, cache); }); const render = useRerender(); React.useEffect(render, [staleWhileRevalidate]); let elm = null; try { elm = component({ ...props, query, mutation, subscription }); } finally { unsubscribe(); } if (!context.shouldFetch) { return elm; } const promise = resolve().finally(render); if (onError) { promise.catch(onError); } if (suspense === true) { throw promise; } else if (typeof suspense === "object") { const Suspender = () => { if (!promise) return null; throw promise; }; return /* @__PURE__ */ React.createElement(React.Suspense, { fallback: suspense.fallback }, /* @__PURE__ */ React.createElement(Suspender, null), elm); } return elm; }; withGraphQL.displayName = `GraphQLComponent(${(component == null ? void 0 : component.displayName) || (component == null ? void 0 : component.name) || "Anonymous"})${Date.now()}`; return withGraphQL; }; return graphql; } export { createGraphqlHOC };