UNPKG

@gqty/react

Version:

The No-GraphQL Client for React

48 lines (45 loc) 1.24 kB
import { useRerender, useThrottledCallback } from '@react-hookz/web'; import { GQtyError } from 'gqty'; import { useMemo, useState, useEffect } from 'react'; function createUseSubscription({ createResolver }) { const useSubscription = ({ onError, operationName, renderThrottleDelay = 100 } = {}) => { const { accessor: { subscription }, subscribe, selections } = useMemo(() => createResolver({ operationName }), [operationName]); const render = useRerender(); const throttledRender = useThrottledCallback( render, [render], renderThrottleDelay ); const [error, setError] = useState(); if (error) throw error; useEffect(() => { return subscribe({ onNext: () => throttledRender(), onError(error2) { const theError = GQtyError.create(error2); if (onError) { onError(theError); } else { setError(theError); } } }); }, [onError, selections, selections.size]); if (!subscription) { throw new GQtyError(`Subscription is not defined in the schema.`); } return subscription; }; return useSubscription; } export { createUseSubscription };