From dd7b03297a62dc3e037fdd543816b9c411698f52 Mon Sep 17 00:00:00 2001 From: Ashelyn Rose Date: Sun, 19 Nov 2023 16:33:33 -0700 Subject: [PATCH] ensure tauri event listener is always unsubscribed previously if a component mounted and then immediately unmounted we may not have received the callback function from tauri this makes it so the promise we receive from tauri is awaited as part of cleanup instead, guaranteeing the unlisten callback is always called (deferring that call until it's available if necessary) --- src/hooks/useTauriEvent.ts | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/hooks/useTauriEvent.ts b/src/hooks/useTauriEvent.ts index e140c5e..63a3819 100644 --- a/src/hooks/useTauriEvent.ts +++ b/src/hooks/useTauriEvent.ts @@ -2,19 +2,17 @@ import {useEffect, useRef, useCallback} from 'react' import { EventCallback, listen, UnlistenFn } from "@tauri-apps/api/event"; export default function useTauriEvent(eventName : string, callback : EventCallback, depArray : any[]) { - const unsubRef = useRef(null) + const unlistenPromiseRef = useRef>() const stableCallback = useCallback(callback, depArray) useEffect(() => { - listen(eventName, stableCallback).then(unlisten => { - unsubRef.current = unlisten - }) + unlistenPromiseRef.current = listen(eventName, stableCallback) return () => { - if (unsubRef.current) { - unsubRef.current() - } + unlistenPromiseRef.current?.then(unlisten => { + unlisten() + }) } }, [eventName, stableCallback]) }