Refactor debounce and tauri event listeners

This commit is contained in:
Gregory Schier
2023-04-01 21:39:46 -07:00
parent 15c22d98c6
commit b0d8908724
11 changed files with 154 additions and 137 deletions

View File

@@ -0,0 +1,22 @@
import type { EventCallback } from '@tauri-apps/api/event';
import { listen as tauriListen } from '@tauri-apps/api/event';
import type { DependencyList } from 'react';
import { useEffect } from 'react';
export function useTauriEvent<T>(event: string, fn: EventCallback<T>, deps: DependencyList = []) {
useEffect(() => {
let unMounted = false;
let unsubFn: (() => void) | undefined = undefined;
tauriListen(event, fn).then((unsub) => {
if (unMounted) unsub();
else unsubFn = unsub;
});
return () => {
unMounted = true;
unsubFn?.();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [event, fn, ...deps]);
}