UNPKG

solid-awesome-hooks

Version:
31 lines (30 loc) 1.11 kB
import { createEffect, on, onCleanup, runWithOwner, getOwner } from "solid-js"; const DEFAULT_OPTIONS = { timeInterval: 3000, enabled: () => true, callLimit: 10, }; /** * * @param readyTrigger Reactive signal that tells that the poll function can now be scheduled * @param poll Function * @param options {UsePollingOptions} */ export const usePolling = (readyTrigger, poll, options) => { const { timeInterval, enabled, owner = getOwner(), callLimit } = Object.assign({}, DEFAULT_OPTIONS, options); const pollWithOwner = () => runWithOwner(owner, () => poll()); let remainingCalls = callLimit; // This effect is triggered when the data signal changes // Thus, we don't rely on slow network createEffect(on([readyTrigger, enabled], ([_, isEnabled]) => { if (remainingCalls <= 0) return; if (!isEnabled) return; const timer = setTimeout(() => { pollWithOwner(); remainingCalls -= 1; }, timeInterval); onCleanup(() => clearTimeout(timer)); })); };