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)
main
Ashelyn Dawn 6 months ago
parent 092fe2a12f
commit dd7b03297a
No known key found for this signature in database
GPG Key ID: D1980B8C6F349BC1

@ -2,19 +2,17 @@ import {useEffect, useRef, useCallback} from 'react'
import { EventCallback, listen, UnlistenFn } from "@tauri-apps/api/event";
export default function useTauriEvent<T>(eventName : string, callback : EventCallback<T>, depArray : any[]) {
const unsubRef = useRef<null|UnlistenFn>(null)
const unlistenPromiseRef = useRef<Promise<UnlistenFn>>()
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])
}

Loading…
Cancel
Save