mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-03-22 17:39:12 +01:00
Refactor debounce and tauri event listeners
This commit is contained in:
22
src-web/hooks/useTauriEvent.ts
Normal file
22
src-web/hooks/useTauriEvent.ts
Normal 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]);
|
||||
}
|
||||
Reference in New Issue
Block a user