According to docs, one should use callbacks to communicate from main to renderer.
When using useEffect
, how can one cleanup window.api.test
using return
function to prevent multiple instances of callback from being fired?
Looking for callback equivalent to addEventListener
and removeEventListener
model.
preload.ts
import { contextBridge, ipcRenderer } from "electron"
export interface API {
test: (callback: () => void) => void
}
const api: API = {
test: (callback) => {
ipcRenderer.on("test", (event) => {
callback()
})
},
}
contextBridge.exposeInMainWorld("api", api)
renderer.tsx
…
useEffect(() => {
window.api.test(() => {
console.log("test fired")
})
return () => {
// Cleanup window.api.test somehow…
}
}, [])
…
CodePudding user response:
A common approach when adding event handlers is to return a function that can be used to remove it.
Unfortunately ipcRenderer.on()
doesn't do this (