UNPKG

relay-hooks

Version:
3 lines (2 loc) 19.8 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("relay-runtime"),require("react"),require("fbjs/lib/areEqual"),require("fbjs/lib/warning"),require("fbjs/lib/invariant"),require("@restart/hooks/useMounted")):"function"==typeof define&&define.amd?define(["exports","relay-runtime","react","fbjs/lib/areEqual","fbjs/lib/warning","fbjs/lib/invariant","@restart/hooks/useMounted"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["relay-hooks"]={},e.relayRuntime,e.React,e.areEqual,e.warning,e.invariant,e.useMounted)}(this,(function(e,t,r,n,i,o,s){"use strict";var a="default"in r?r.default:r;n=n&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n,i=i&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i,o=o&&Object.prototype.hasOwnProperty.call(o,"default")?o.default:o,s=s&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s;var u=(0,t.__internal.createRelayContext)(a),l={force:!0};function c(e,r,n){return t.createOperationDescriptor(t.getRequest(e),r,n)}var f=t.__internal.fetchQuery;function h(e){var t,r,n,i,o=e.doRetain,s=void 0===o||o,a=e.disposeTemporary,u=null,l=null,c=!1,h=null,d=function(e,t){void 0===t&&(t=null),c=e,h=t},p=function(){v(),l&&l.dispose(),g(),l=null,i=null,r=null},v=function(){clearTimeout(t),t=null},g=function(){u&&u.unsubscribe(),h=null,c=!1};return{fetch:function(e,t,o,a,h,v,m){void 0===o&&(o="network-only"),void 0===a&&(a=function(e,t){});var b=!1;i==e&&r.request.identifier===t.request.identifier||(p(),s&&(l=e.retain(t))),i=e,r=t,g();var y,R,_=function(e,t,r,n){if("network-only"!==r){var i=e.check(t).status,o="available"===i;if(o||"partial"===n&&"stale"!==i)return{snapshot:e.lookup(t.fragment),full:o}}return{snapshot:null,full:!1}}(e,t,o,m),P=_.snapshot,k="network-only"===(R=o)||"store-and-network"===R||"store-or-network"===R&&!_.full;if(null!=P){var q=!k;h(t,P,b&&!q),q&&a(null,b)}if(u&&u.unsubscribe(),k){var E=function(){},w=function(){u===y&&(u=null),c=!1,n=null},F=function(e){void 0===e&&(e=null),E(),d(!1,e),w(),a(e,b)};f(e,t).subscribe({unsubscribe:function(){w()},complete:F,error:function(e){return F(e)},next:function(r){var i=e.lookup(t.fragment);n=null;var o=Array.isArray(r)?r:[r],s=t.request.cacheConfig,a=!!s&&!!s.poll,u=o.some((function(e){return null!=e&&!0===e.hasNext}));a&&d(!1),E(),v&&v(r),h(t,i,b&&(u||a))},start:function(e){u=y=e,d(!0)}}),P||(n=new Promise((function(e){E=e})))}return b=!0,{dispose:function(){y&&y.unsubscribe()}}},getData:function(){return{isLoading:c,error:h}},dispose:p,checkAndSuspense:function(e,r){v();var i=n||h;if(e&&i)throw n&&r&&(t=setTimeout((function(){v(),p(),a&&a()}),3e4)),i;return i}}}var d=new Map;function p(e,t,r,n){var i=c(t,r,n),o=e&&d.has(i.request.identifier)?d.get(i.request.identifier):new g;return o.setQuery(t,r,n,i),o}var v=function(){},g=function(){function e(){var e=this;this.forceUpdate=v,this.result=null,this.retry=function(t,r){void 0===r&&(r={});var n=r.fetchPolicy,i=void 0===n?"network-only":n,o=t?c(e.query.request.node,e.query.request.variables,t):e.query;e.fetch(o,i,r),e.resolveResult(),e.forceUpdate()},this.result={retry:this.retry,error:null,data:null,isLoading:!1},this.fetcher=h({disposeTemporary:function(){e.dispose(),e.query&&d.delete(e.query.request.identifier)}})}return e.prototype.setQuery=function(e,t,r,n){this.gqlQuery=e,this.variables=t,this.query=n,this.cacheConfig=r},e.prototype.getForceUpdate=function(){return this.forceUpdate},e.prototype.setForceUpdate=function(e){this.forceUpdate=e},e.prototype.dispose=function(){this.fetcher.dispose(),this.disposeSnapshot()},e.prototype.disposeSnapshot=function(){this.snapshot=null,this.rootSubscription&&(this.rootSubscription.dispose(),this.rootSubscription=null)},e.prototype.fetch=function(e,t,r,n){var i=this;if(this.disposeSnapshot(),n)this.fetcher.dispose();else{var o=r.onComplete,s=function(e){i.resolveResult(),e&&i.forceUpdate()};this.fetcher.fetch(this.environment,e,t,(function(e,t){s(t),o&&o(e)}),(function(e,t,r){i.snapshot||(i.snapshot=t,i.subscribe(t),s(r))}),r.onResponse,r.UNSTABLE_renderPolicy)}},e.prototype.getQuery=function(e,t,r){return e==this.gqlQuery&&r==this.cacheConfig&&t==this.variables&&n(t,this.variables)?this.query:(this.variables=t,this.gqlQuery=e,this.cacheConfig=r,c(e,t,r))},e.prototype.resolveEnvironment=function(e){this.resolve(e,this.gqlQuery,this.variables,this.options)},e.prototype.resolve=function(e,t,r,n){var i=this.getQuery(t,r,n.networkCacheConfig),o=n.fetchPolicy,s=void 0===o?"store-or-network":o,a=n.fetchKey,u=n.skip;this.options=n,(!this.query||i.request.identifier!==this.query.request.identifier||e!==this.environment||s!==this.fetchPolicy||a!==this.fetchKey||u!==this.skip)&&(this.environment=e,this.query=i,this.skip=u,this.fetchPolicy=s,this.fetchKey=a,this.fetch(i,s,n,u),this.resolveResult())},e.prototype.checkAndSuspense=function(e,t){t&&(this.setForceUpdate(v),d.set(this.query.request.identifier,this));var r=this.fetcher.checkAndSuspense(e,t);return t&&d.delete(this.query.request.identifier),r},e.prototype.getData=function(){return this.result},e.prototype.resolveResult=function(){var e=this.fetcher.getData(),r=e.error,n=e.isLoading,i=this.snapshot;i&&i.missingRequiredFields&&t.handlePotentialSnapshotErrors(this.environment,i.missingRequiredFields,i.relayResolverErrors),this.result={retry:this.retry,error:r,data:i?i.data:null,isLoading:n}},e.prototype.subscribe=function(e){var t=this;this.rootSubscription&&this.rootSubscription.dispose(),this.rootSubscription=this.environment.subscribe(e,(function(e){t.snapshot=e,t.resolveResult(),t.forceUpdate()}))},e}();function m(){var e=r.useState([])[1],t=r.useRef({mounted:!1,pending:!1});return r.useEffect((function(){return t.current.mounted=!0,t.current.pending&&(t.current.pending=!1,e([])),function(){t.current={mounted:!1,pending:!1}}}),[]),r.useCallback((function(){t.current.mounted?e([]):t.current.pending=!0}),[e])}function b(){return a.useContext(u).environment}var y=function(e,t,n,i){var o=b(),s=m(),a=r.useRef(void 0),u=r.useRef(!1);null!=a.current&&1!=u.current||(a.current={queryFetcher:p(i,e,t,n.networkCacheConfig)},u.current=!1),r.useEffect((function(){return 1==u.current&&s(),function(){a.current.queryFetcher.dispose(),u.current=!0}}),[]);var l=a.current.queryFetcher;return l.resolve(o,e,t,n),l.checkAndSuspense(i,i),l.setForceUpdate(s),l.getData()},R=function(){},_=function(e){void 0===e&&(e=!1);var t=new g;return{next:function(e,r,n,i){var o;void 0===n&&(n={}),void 0===i&&(i={}),i.networkCacheConfig=null!==(o=i.networkCacheConfig)&&void 0!==o?o:l,t.resolve(e,r,n,i);var s=t.checkAndSuspense();return s?s instanceof Error?Promise.reject(s):s:Promise.resolve()},subscribe:function(e){return t.setForceUpdate(e),function(){t.getForceUpdate()===e&&t.setForceUpdate(R)}},getValue:function(r){return t.resolveEnvironment(r),t.checkAndSuspense(e),t.getData()},dispose:function(){t.dispose(),t.setForceUpdate(R),t=new g}}},P=function(){return(P=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e}).apply(this,arguments)};function k(e,r,n){var i,s;if(null==n)return{cursor:null,hasMore:!1};var a=t.ConnectionInterface.get(),u=a.EDGES,l=a.PAGE_INFO,c=a.HAS_NEXT_PAGE,f=a.HAS_PREV_PAGE,h=a.END_CURSOR,d=a.START_CURSOR;"object"!=typeof n&&o(!1);var p=n[u],v=n[l];if(null==p||null==v)return{cursor:null,hasMore:!1};Array.isArray(p)||o(!1),"object"!=typeof v&&o(!1);var g="forward"===e?null!==(i=v[h])&&void 0!==i?i:null:null!==(s=v[d])&&void 0!==s?s:null;return null!==g&&"string"!=typeof g&&o(!1),{cursor:g,hasMore:"forward"===e?null!=g&&!0===v[c]:null!=g&&!0===v[f]}}var q=t.__internal.getPromiseForActiveRequest;function E(){}function w(e){var t=F(e);return Array.isArray(e)?{snapshot:e,data:e.map((function(e){return e.data})),isMissingData:t}:{snapshot:e,data:e.data,isMissingData:t}}function F(e){return Array.isArray(e)?e.some((function(e){return e.isMissingData})):e.isMissingData}var S=function(){function e(e){var r=this;this.unmounted=!1,this.refetchable=!1,this.pagination=!1,this.refetch=function(e,n){var i,o,s,a;if(void 0===n&&(n={}),!0===r.unmounted)return{dispose:E};var u,f,h=t.getRefetchMetadata(r._fragment,r.name),d=h.fragmentRefPathInResponse,p=h.identifierInfo,v=h.refetchableRequest,g=r.getData().data,m=null!=(null==p?void 0:p.identifierField)&&null!=g&&"object"==typeof g?g[p.identifierField]:null;null==r._selector?(u={},f={}):"PluralReaderSelector"===r._selector.kind?(u=null!==(o=null===(i=r._selector.selectors[0])||void 0===i?void 0:i.owner.variables)&&void 0!==o?o:{},f=null!==(a=null===(s=r._selector.selectors[0])||void 0===s?void 0:s.variables)&&void 0!==a?a:{}):(u=r._selector.owner.variables,f=r._selector.variables);var b=P(P(P({},u),f),e);null==p||e.hasOwnProperty(p.identifierQueryVariableName)||(b[p.identifierQueryVariableName]=m),r.pagination&&(r.fetcherNext.dispose(),r.fetcherPrevious.dispose());var y=c(v,b,l),R=r.fetcherRefecth.fetch(r._environment,y,n.fetchPolicy,(function(e,t){t&&r.refreshHooks(),n.onComplete&&n.onComplete(e)}),(function(e,n,i){var o=t.getValueAtPath(n.data,d),s=r.isEqualsFragmentRef(r._fragmentRefRefetch||r._fragmentRef,o),a=F(n);s&&!a||(r._fragmentRefRefetch=o,r._idfragmentrefetch=t.getFragmentIdentifier(r._fragment,o),r.lookup(r._fragment,o),r.subscribe(),r.resolverData.isMissingData=a,r.resolverData.owner=e.request,i&&r.refreshHooks())}),n.onResponse,n.UNSTABLE_renderPolicy);return r.refreshHooks(),R},this.loadPrevious=function(e,t){return r.loadMore("backward",e,t)},this.loadNext=function(e,t){return r.loadMore("forward",e,t)},this.loadMore=function(e,n,i){var s;void 0===i&&(i={});var a=null!==(s=i.onComplete)&&void 0!==s?s:E,u=r.getData().data,f={dispose:E},h="backward"===e?r.fetcherPrevious:r.fetcherNext;if(!0===r.unmounted)return f;if(null==r._selector)return a(null),f;if(r._environment.isRequestActive(r._selector.owner.identifier)||!0===h.getData().isLoading||null==u)return a(null),f;(null==r._selector||"PluralReaderSelector"===r._selector.kind)&&o(!1);var d=t.getPaginationMetadata(r._fragment,r.name),p=d.paginationRequest,v=d.paginationMetadata,g=d.connectionPathInFragmentData,m=t.getRefetchMetadata(r._fragment,r._fragment.name).identifierInfo,b=null!=m&&null!=u&&"object"==typeof u?u[m.identifierField]:null,y=r._selector.variables,R=i.UNSTABLE_extraVariables,_=P(P({},r._selector.owner.variables),y),q=function(e,r,n,i){return k(e,0,t.getValueAtPath(n,i))}(e,0,u,g).cursor,w=t.getPaginationVariables(e,n,q,_,P({},R),v);null!=m&&(w[m.identifierQueryVariableName]=b);var F=c(p,w,l),S=h.fetch(r._environment,F,void 0,(function(e,t){t&&r.refreshHooks(),a(e)}),E,i.onResponse);return r.refreshHooks(),S},this.name=e,this.pagination="usePagination"===e,this.refetchable="useRefetchable"===e||this.pagination,this.refetchable&&(this.fetcherRefecth=h({doRetain:!0})),this.pagination&&(this.fetcherNext=h({}),this.fetcherPrevious=h({})),this.setForceUpdate(),this.refreshHooks=function(){r.resolveResult(),r.forceUpdate()}}return e.prototype.setForceUpdate=function(e){void 0===e&&(e=E),this.forceUpdate=e},e.prototype.subscribeResolve=function(e){this._subscribeResolve&&this._subscribeResolve!=e&&e(this.getData()),this._subscribeResolve=e},e.prototype.setUnmounted=function(){this.unmounted=!0},e.prototype.isEqualsFragmentRef=function(e,r){if(this._fragmentRef!==r){var i=t.getDataIDsFromFragment(this._fragment,e),o=t.getDataIDsFromFragment(this._fragment,r);if(!n(i,o)||!n(this.getFragmentVariables(r),this.getFragmentVariables(e)))return!1}return!0},e.prototype.dispose=function(){this.unsubscribe(),this.fetcherNext&&this.fetcherNext.dispose(),this.fetcherPrevious&&this.fetcherPrevious.dispose(),this._idfragmentrefetch=null,this._fragmentRefRefetch=null,this.fetcherRefecth&&this.fetcherRefecth.dispose()},e.prototype.getFragmentVariables=function(e){return void 0===e&&(e=this._fragmentRef),t.getVariablesFromFragment(this._fragment,e)},e.prototype.resolve=function(e,t,r,n){(!this.resolverData||this._environment!==e||t!==this._idfragment&&(!this._idfragmentrefetch||this._idfragmentrefetch&&t!==this._idfragmentrefetch))&&(this._fragment=r,this._fragmentRef=n,this._idfragment=t,this._selector=null,this.dispose(),this._environment=e,this.lookup(r,this._fragmentRef),this.resolveResult())},e.prototype.lookup=function(e,r){if(null!=r)if(e.metadata&&e.metadata.plural&&!0===e.metadata.plural&&0===r.length)this.resolverData={data:[]};else{this._selector=t.getSelector(e,r);var n,i,o=(n=this._environment,"PluralReaderSelector"===(i=this._selector).kind?i.selectors.map((function(e){return n.lookup(e)})):n.lookup(i));this.resolverData=w(o),this.resolverData.owner=this._selector?"PluralReaderSelector"===this._selector.kind?this._selector.selectors[0].owner:this._selector.owner:null}else this.resolverData={data:null}},e.prototype.checkAndSuspense=function(e){var t,r=this;if(e&&this.resolverData.isMissingData&&this.resolverData.owner){var n=this.resolverData.owner,i=function(e,t,r){var n,i,o,s=q(r,t);if(null!=s)o=t.node.params.name;else{var a=r.getOperationTracker().getPendingOperationsAffectingOwner(t),u=null==a?void 0:a.pendingOperations;s=null!==(n=null==a?void 0:a.promise)&&void 0!==n?n:null,o=null!==(i=null==u?void 0:u.map((function(e){return e.node.params.name})).join(","))&&void 0!==i?i:null}if(!s)return null;null!=o&&0!==o.length||(o="Unknown pending operation");var l=e.name,c=o===l?"Relay(".concat(o,")"):"Relay(".concat(o,":").concat(l,")");return s.displayName=c,s}(this._fragment,n,this._environment),o=null!==(t=n.node.params.name)&&void 0!==t?t:"Unknown Parent Query";if(null!=i){var s=i.then((function(){r._idfragmentrefetch?r.resolveResult():(r._idfragment=null,r.dispose())})).catch((function(e){r._idfragmentrefetch?r.resolveResult():(r._idfragment=null,r.dispose())}));throw s.displayName="Relay("+o+")",this.unsubscribe(),this.refreshHooks=E,s}}this.fetcherRefecth&&this.fetcherRefecth.checkAndSuspense(e)},e.prototype.getData=function(){return this.result},e.prototype.resolveResult=function(){var e=this.resolverData.data;if(this.refetchable||this.pagination){var r=this.fetcherRefecth.getData(),n=r.isLoading,i=r.error,o=this.refetch;if(this.pagination){var s=t.getPaginationMetadata(this._fragment,this.name).connectionPathInFragmentData,a=t.getValueAtPath(e,s),u=k("forward",0,a).hasMore,l=k("backward",0,a).hasMore,c=this.fetcherNext.getData(),f=c.isLoading,h=c.error,d=this.fetcherPrevious.getData();this.result={data:e,hasNext:u,isLoadingNext:f,hasPrevious:l,isLoadingPrevious:d.isLoading,isLoading:n,errorNext:h,errorPrevious:d.error,error:i,refetch:o,loadNext:this.loadNext,loadPrevious:this.loadPrevious}}else this.result={data:e,isLoading:n,error:i,refetch:o}}else this.result=e;var p=this.resolverData.snapshot;p&&this._throwOrLogErrorsInSnapshot(p),this._subscribeResolve&&this._subscribeResolve(this.result)},e.prototype.unsubscribe=function(){this._disposable&&this._disposable.dispose()},e.prototype.subscribe=function(){var e=this,t=this._environment,r=this.resolverData.snapshot;this.unsubscribe();var n=[];r&&(Array.isArray(r)?r.forEach((function(r,i){n.push(t.subscribe(r,(function(t){e.resolverData.snapshot[i]=t,e.resolverData.data[i]=t.data,e.resolverData.isMissingData=F(e.resolverData.snapshot),e.refreshHooks()})))})):n.push(t.subscribe(r,(function(t){e.resolverData=w(t),e.refreshHooks()})))),this._disposable={dispose:function(){n.map((function(e){return e.dispose()})),e._disposable=void 0}}},e.prototype._throwOrLogErrorsInSnapshot=function(e){var r=this;Array.isArray(e)?e.forEach((function(e){e.missingRequiredFields&&t.handlePotentialSnapshotErrors(r._environment,e.missingRequiredFields,e.relayResolverErrors)})):e.missingRequiredFields&&t.handlePotentialSnapshotErrors(this._environment,e.missingRequiredFields,e.relayResolverErrors)},e}();function D(e,n,i,o,s){var a=b(),u=m(),l=r.useRef(null),c=r.useRef(!1);(null==l.current||c.current)&&(l.current={resolver:new S(o)},c.current=!1);var f=l.current.resolver;r.useEffect((function(){return 1==c.current&&u(),function(){l.current.resolver.setUnmounted(),c.current=!0}}),[]),r.useEffect((function(){return function(){f.dispose()}}),[f]);var h=r.useMemo((function(){return t.getFragment(e)}),[e]),d=r.useMemo((function(){return t.getFragmentIdentifier(h,n)}),[h,n]);if(r.useEffect((function(){return f.subscribe(),function(){f.unsubscribe()}}),[f,d,a]),f.subscribeResolve(s),f.resolve(a,d,h,n),!s)return f.checkAndSuspense(i),f.setForceUpdate(u),[f.getData(),f]}var A=a.useCallback,O=a.useState;Object.defineProperty(e,"applyOptimisticMutation",{enumerable:!0,get:function(){return t.applyOptimisticMutation}}),Object.defineProperty(e,"commitLocalUpdate",{enumerable:!0,get:function(){return t.commitLocalUpdate}}),Object.defineProperty(e,"commitMutation",{enumerable:!0,get:function(){return t.commitMutation}}),Object.defineProperty(e,"fetchQuery",{enumerable:!0,get:function(){return t.fetchQuery}}),Object.defineProperty(e,"graphql",{enumerable:!0,get:function(){return t.graphql}}),Object.defineProperty(e,"requestSubscription",{enumerable:!0,get:function(){return t.requestSubscription}}),e.FORWARD="forward",e.FRAGMENT_NAME="useFragment",e.NETWORK_ONLY="network-only",e.PAGINATION_NAME="usePagination",e.REFETCHABLE_NAME="useRefetchable",e.ReactRelayContext=u,e.RelayEnvironmentProvider=function(e){var t=a.useMemo((function(){return{environment:e.environment}}),[e.environment]);return a.createElement(u.Provider,{value:t},e.children)},e.STORE_ONLY="store-only",e.STORE_OR_NETWORK="store-or-network",e.STORE_THEN_NETWORK="store-and-network",e.loadLazyQuery=function(){return _(!0)},e.loadQuery=function(){return _(!1)},e.useFragment=function(e,t){return D(e,t,!1,"useFragment")[0]},e.useFragmentSubscription=function(e,t,r){D(e,t,!1,"useFragment",r)},e.useLazyLoadQuery=function(e,t,r){var n;return void 0===t&&(t={}),void 0===r&&(r={}),r.networkCacheConfig=null!==(n=r.networkCacheConfig)&&void 0!==n?n:l,y(e,t,r,!0)},e.useMutation=function(e,r,n){void 0===r&&(r={});var i=O({loading:!1,data:null,error:null}),a=i[0],u=i[1],l=s(),c=b(),f=n||c,h=r.configs,d=r.variables,p=r.uploadables,v=r.onCompleted,g=r.onError,m=r.optimisticUpdater,y=r.optimisticResponse,R=r.updater;return[A((function(r){var n=P({configs:h,variables:d,uploadables:p,onCompleted:v,onError:g,optimisticUpdater:m,optimisticResponse:y,updater:R},r);return n.variables||o(!1),l()&&u({loading:!0,data:n.optimisticResponse,error:null}),new Promise((function(r,i){function o(e){l()&&u({loading:!1,data:null,error:e}),n.onError?(n.onError(e),r(null)):i(e)}t.commitMutation(f,P(P({},n),{mutation:e,variables:n.variables,onCompleted:function(e,t){t?o(t):(l()&&u({loading:!1,data:e,error:null}),n.onCompleted&&n.onCompleted(e),r(e))},onError:o}))}))}),[f,h,e,d,p,v,g,m,y,R,l]),a]},e.useOssFragment=D,e.usePagination=function(e,t){return D(e,t,!1,"usePagination")[0]},e.usePaginationFragment=function(e,t){return D(e,t,!0,"usePagination")[0]},e.usePaginationSubscription=function(e,t,r){D(e,t,!1,"usePagination",r)},e.usePreloadedQuery=function(e){var t=m(),n=b();return r.useEffect((function(){return e.subscribe(t)}),[e]),e.getValue(n)},e.useQuery=function(e,t,r){return void 0===t&&(t={}),void 0===r&&(r={}),y(e,t,r,!1)},e.useRefetchable=function(e,t){return D(e,t,!1,"useRefetchable")[0]},e.useRefetchableFragment=function(e,t){return D(e,t,!0,"useRefetchable")[0]},e.useRefetchableSubscription=function(e,t,r){D(e,t,!1,"useRefetchable",r)},e.useRelayEnvironment=b,e.useSubscription=function(e,n){var i=b(),o=n&&n.skip;r.useEffect((function(){if(!o)return t.requestSubscription(i,e).dispose}),[i,e,o])},e.useSuspenseFragment=function(e,t){return D(e,t,!0,"useFragment")[0]},Object.defineProperty(e,"__esModule",{value:!0})})); //# sourceMappingURL=relay-hooks.min.js.map