You've already forked joplin
mirror of
https://github.com/laurent22/joplin.git
synced 2025-11-23 22:36:32 +02:00
Desktop: Multiple window support (#11181)
Co-authored-by: Laurent Cozic <laurent22@users.noreply.github.com>
This commit is contained in:
29
packages/lib/hooks/useNowEffect.test.ts
Normal file
29
packages/lib/hooks/useNowEffect.test.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import type * as React from 'react';
|
||||
import { renderHook } from '@testing-library/react-hooks';
|
||||
import useNowEffect from './useNowEffect';
|
||||
|
||||
describe('useNowEffect', () => {
|
||||
test('should call the cleanup callback when the effect function is called and after unmount', async () => {
|
||||
const cleanupFunction = jest.fn(() => {});
|
||||
const effectFunction = jest.fn(() => cleanupFunction);
|
||||
const useTestHook = (dependencies: React.DependencyList) => {
|
||||
return useNowEffect(effectFunction, dependencies);
|
||||
};
|
||||
|
||||
const hook = renderHook(useTestHook, { initialProps: [0] });
|
||||
expect(cleanupFunction).not.toHaveBeenCalled();
|
||||
expect(effectFunction).toHaveBeenCalledTimes(1);
|
||||
|
||||
hook.rerender([0]);
|
||||
expect(cleanupFunction).not.toHaveBeenCalled();
|
||||
expect(effectFunction).toHaveBeenCalledTimes(1);
|
||||
|
||||
hook.rerender([1]);
|
||||
expect(cleanupFunction).toHaveBeenCalledTimes(1);
|
||||
expect(effectFunction).toHaveBeenCalledTimes(2);
|
||||
|
||||
hook.unmount();
|
||||
expect(cleanupFunction).toHaveBeenCalledTimes(2);
|
||||
expect(effectFunction).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
28
packages/lib/hooks/useNowEffect.ts
Normal file
28
packages/lib/hooks/useNowEffect.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import type * as React from 'react';
|
||||
import shim from '../shim';
|
||||
|
||||
type CleanupCallback = (()=> void)|null;
|
||||
export type EffectFunction = ()=> CleanupCallback;
|
||||
const { useRef, useMemo, useEffect } = shim.react();
|
||||
|
||||
// Like useEffect, but runs as soon as possible.
|
||||
const useNowEffect = (effect: EffectFunction, dependencies: React.DependencyList) => {
|
||||
const lastCleanup = useRef<CleanupCallback>(null);
|
||||
|
||||
const cleanupCallback = useMemo(() => {
|
||||
lastCleanup.current?.();
|
||||
lastCleanup.current = null;
|
||||
|
||||
return effect() ?? null;
|
||||
// eslint-disable-next-line @seiyab/react-hooks/exhaustive-deps -- This is a custom hook
|
||||
}, dependencies);
|
||||
lastCleanup.current = cleanupCallback;
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
lastCleanup.current?.();
|
||||
lastCleanup.current = null;
|
||||
};
|
||||
}, []);
|
||||
};
|
||||
export default useNowEffect;
|
||||
Reference in New Issue
Block a user