Skip to content

Commit

Permalink
feat: add ability to deactivate auto update
Browse files Browse the repository at this point in the history
  • Loading branch information
marlontrapp committed Feb 2, 2023
1 parent 3f35abe commit ae40a34
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
13 changes: 9 additions & 4 deletions src/context/provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export type SettingsValue = Pick<SettingsProviderValue, 'settings' | 'flags'>;
type SettingsProviderOptions = {
updateIntervalMs?: number;
onGetSettingsFail?: 'keep-last' | 'reset';
autoUpdate?: boolean;
};

interface Props {
Expand All @@ -23,7 +24,7 @@ const initialValue = { flags: {}, settings: {} };
export function SettingsProvider({
children,
getSettings,
options: { onGetSettingsFail = 'keep-last', updateIntervalMs = tenMinInMs } = {},
options: { onGetSettingsFail = 'keep-last', updateIntervalMs = tenMinInMs, autoUpdate = true } = {},
}: Props): ReactElement<Props> {
const [isLoading, setLoading] = useState(false);
const [value, setValue] = useState<SettingsValue>(initialValue);
Expand All @@ -46,11 +47,15 @@ export function SettingsProvider({
}

load();

const intervalId = window.setInterval(load, updateIntervalMs);
let intervalId: number | null = null;
if (autoUpdate) {
intervalId = window.setInterval(load, updateIntervalMs);
}

return function cleanup() {
window.clearInterval(intervalId);
if (intervalId) {
window.clearInterval(intervalId);
}
};
}, []);

Expand Down
29 changes: 29 additions & 0 deletions tests/context/provider.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -118,4 +118,33 @@ describe('SettingsProvider', () => {
expect(getRendered()).toStrictEqual({ flags: {}, settings: {}, isLoading: false });
});
});

describe('test updateIntervalMs', () => {
beforeEach(jest.useFakeTimers);
afterEach(jest.useRealTimers);

it('calls get settings after delay', async () => {
const getSettings = jest.fn().mockResolvedValueOnce(settings).mockRejectedValueOnce({}) as Props['getSettings'];
const options = { updateIntervalMs: 10000 } as Props['options'];
setup({ getSettings, options });

await waitFor(() => expect(getSettings).toHaveBeenCalledTimes(1));
act(() => {
jest.advanceTimersByTime(10000);
});
await waitFor(() => expect(getSettings).toHaveBeenCalledTimes(2));
});

it('does no call get settings after delay if deactivated', async () => {
const getSettings = jest.fn().mockResolvedValueOnce(settings).mockRejectedValueOnce({}) as Props['getSettings'];
const options = { updateIntervalMs: 10000, autoUpdate: false } as Props['options'];
setup({ getSettings, options });

await waitFor(() => expect(getSettings).toHaveBeenCalledTimes(1));
act(() => {
jest.advanceTimersByTime(10000);
});
await waitFor(() => expect(getSettings).toHaveBeenCalledTimes(1));
});
});
});

0 comments on commit ae40a34

Please sign in to comment.