Skip to content

Commit

Permalink
feat: multichain polling hook (#12171)
Browse files Browse the repository at this point in the history
<!--
Please submit this PR as a draft initially.
Do not mark it as "Ready for review" until the template has been
completely filled out, and PR status checks have passed at least once.
-->

## **Description**

Adds a `usePolling` hook that handles starting and stopping polling
loops for polling controllers. This will be used to poll across chains,
and eventually make more polling UI based so we're only polling data
when UI components require it.


## **Related issues**


## **Manual testing steps**


## **Screenshots/Recordings**

<!-- If applicable, add screenshots and/or recordings to visualize the
before and after of your change. -->

### **Before**

<!-- [screenshots/recordings] -->

### **After**

<!-- [screenshots/recordings] -->

## **Pre-merge author checklist**

- [ ] I’ve followed [MetaMask Contributor
Docs](https://github.com/MetaMask/contributor-docs) and [MetaMask Mobile
Coding
Standards](https://github.com/MetaMask/metamask-mobile/blob/main/.github/guidelines/CODING_GUIDELINES.md).
- [ ] I've completed the PR template to the best of my ability
- [ ] I’ve included tests if applicable
- [ ] I’ve documented my code using [JSDoc](https://jsdoc.app/) format
if applicable
- [ ] I’ve applied the right labels on the PR (see [labeling
guidelines](https://github.com/MetaMask/metamask-mobile/blob/main/.github/guidelines/LABELING_GUIDELINES.md)).
Not required for external contributors.

## **Pre-merge reviewer checklist**

- [ ] I've manually tested the PR (e.g. pull and build branch, run the
app, test code being changed).
- [ ] I confirm that this PR addresses all acceptance criteria described
in the ticket it closes and includes the necessary testing evidence such
as recordings and or screenshots.

---------

Co-authored-by: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net>
Co-authored-by: sahar-fehri <sahar.fehri@consensys.net>
  • Loading branch information
3 people authored Nov 11, 2024
1 parent 61ab41a commit 940258e
Show file tree
Hide file tree
Showing 2 changed files with 93 additions and 0 deletions.
38 changes: 38 additions & 0 deletions app/components/hooks/usePolling.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { renderHook } from '@testing-library/react-hooks';

import usePolling from './usePolling';

describe('usePolling', () => {

it('Should start/stop polling when inputs are added/removed, and stop on dismount', async () => {

const inputs = ['foo', 'bar'];
const mockStartPolling = jest.fn().mockImplementation((input) => `${input}_token`);
const mockStopPollingByPollingToken = jest.fn();

const { unmount, rerender } = renderHook(() =>
usePolling({
startPolling: mockStartPolling,
stopPollingByPollingToken: mockStopPollingByPollingToken,
input: inputs,
})
);

// All inputs should start polling
for (const input of inputs) {
expect(mockStartPolling).toHaveBeenCalledWith(input);
}

// Remove one input, and add another
inputs[0] = 'baz';
rerender({ input: inputs });
expect(mockStopPollingByPollingToken).toHaveBeenCalledWith('foo_token');
expect(mockStartPolling).toHaveBeenCalledWith('baz');

// All inputs should stop polling on dismount
unmount();
for (const input of inputs) {
expect(mockStopPollingByPollingToken).toHaveBeenCalledWith(`${input}_token`);
}
});
});
55 changes: 55 additions & 0 deletions app/components/hooks/usePolling.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { useEffect, useRef } from 'react';

interface UsePollingOptions<PollingInput> {
startPolling: (input: PollingInput) => string;
stopPollingByPollingToken: (pollingToken: string) => void;
input: PollingInput[];
}

// A hook that manages multiple polling loops of a polling controller.
// Callers provide an array of inputs, and the hook manages starting
// and stopping polling loops for each input.
const usePolling = <PollingInput>(
usePollingOptions: UsePollingOptions<PollingInput>,
) => {

const pollingTokens = useRef<Map<string, string>>(new Map());

useEffect(() => {
// start new polls
for (const input of usePollingOptions.input) {
const key = JSON.stringify(input);
if (!pollingTokens.current.has(key)) {
const token = usePollingOptions.startPolling(input);
pollingTokens.current.set(key, token);
}
}

// stop existing polls
for (const [inputKey, token] of pollingTokens.current.entries()) {
const exists = usePollingOptions.input.some(
(i) => inputKey === JSON.stringify(i),
);

if (!exists) {
usePollingOptions.stopPollingByPollingToken(token);
pollingTokens.current.delete(inputKey);
}
}
},
// stringified for deep equality
// eslint-disable-next-line react-hooks/exhaustive-deps
[usePollingOptions.input && JSON.stringify(usePollingOptions.input)]);

// stop all polling on dismount
useEffect(() => () => {
for (const token of pollingTokens.current.values()) {
usePollingOptions.stopPollingByPollingToken(token);
}
},
// Intentionally empty to trigger on dismount
// eslint-disable-next-line react-hooks/exhaustive-deps
[]);
};

export default usePolling;

0 comments on commit 940258e

Please sign in to comment.