on master help sign in
bridge/src/lib/useRollerPoller.ts
44 lines 1.7 kB history raw
1import { useEffect, useState } from 'react';
2import { useRollerStore } from 'store/rollerStore';
3import { useTimerStore } from 'store/timerStore';
4import { useInvites } from 'views/Invite/useInvites';
5import { ONE_SECOND, TEN_SECONDS } from './constants';
6import useRoller from './useRoller';
7import { getTimeToNextBatch } from './utils/roller';
9export function useRollerPoller() {
10 const { nextBatchTime, setNextBatchTime, setNextRoll } = useTimerStore();
11 const { point } = useRollerStore();
12 const { api, getPendingTransactions } = useRoller();
13 const { getInvites } = useInvites();
14 const [time, setTime] = useState(ONE_SECOND);
16 useEffect(() => {
17 const interval = setInterval(async () => {
18 const nextRoll = getTimeToNextBatch(nextBatchTime, new Date().getTime());
19 setNextRoll(nextRoll);
21 if (nextBatchTime - ONE_SECOND <= new Date().getTime()) {
22 const response = await api.getRollerConfig();
24 if (response.nextBatch === nextBatchTime) {
25 // exponentially back off or cap at polling every minute
26 setTime(Math.min(60 * ONE_SECOND, time + time));
27 return;
28 }
30 setTime(ONE_SECOND); // reset the timer
31 setNextBatchTime(response.nextBatch);
32 getPendingTransactions();
34 setTimeout(() => {
35 if (!point.isDefault) {
36 getInvites(); // This will also get pending txns
37 }
38 }, TEN_SECONDS); // Should this be more like a minute?
39 }
40 }, time);
42 return () => clearInterval(interval);
43 }, [time, point, nextBatchTime, getPendingTransactions, getInvites]); // eslint-disable-line react-hooks/exhaustive-deps