Skip to content

Commit a94a615

Browse files
committed
feat: return unsub fn
1 parent 3efe737 commit a94a615

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

electron/preload/index.d.ts

+3-1
Original file line numberDiff line numberDiff line change
@@ -58,11 +58,12 @@ declare const appAPI: {
5858
sendCommand: (command: string) => Promise<void>;
5959
/**
6060
* Allows the renderer to subscribe to messages from the main process.
61+
* Returns an unsubscribe function, useful in react hook cleanup functions.
6162
*/
6263
onMessage: (
6364
channel: string,
6465
callback: (event: Electron.IpcRendererEvent, ...args: any[]) => void
65-
) => void;
66+
) => OnMessageUnsubscribe;
6667
/**
6768
* Allows the renderer to unsubscribe from messages from the main process.
6869
* Removes all listeners added by the `onMessage` API for a channel.
@@ -75,6 +76,7 @@ declare const appAPI: {
7576
removeAllListeners(channel: string): void;
7677
};
7778
declare global {
79+
type OnMessageUnsubscribe = () => void;
7880
type TypeOfAppAPI = typeof appAPI;
7981
type AppAPI = {
8082
[K in keyof TypeOfAppAPI]: TypeOfAppAPI[K];

electron/preload/index.ts

+9-2
Original file line numberDiff line numberDiff line change
@@ -80,12 +80,17 @@ const appAPI = {
8080
},
8181
/**
8282
* Allows the renderer to subscribe to messages from the main process.
83+
* Returns an unsubscribe function, useful in react hook cleanup functions.
8384
*/
8485
onMessage: (
8586
channel: string,
8687
callback: (event: IpcRendererEvent, ...args: Array<any>) => void
87-
) => {
88+
): OnMessageUnsubscribe => {
8889
ipcRenderer.on(channel, callback);
90+
91+
return () => {
92+
ipcRenderer.off(channel, callback);
93+
};
8994
},
9095
/**
9196
* Allows the renderer to unsubscribe from messages from the main process.
@@ -96,12 +101,14 @@ const appAPI = {
96101
* is regenerated. To prevent this, ensure to unsubscribe in the hook's
97102
* destroy function. https://stackoverflow.com/a/73458622/470818
98103
*/
99-
removeAllListeners(channel: string) {
104+
removeAllListeners(channel: string): void {
100105
ipcRenderer.removeAllListeners(channel);
101106
},
102107
};
103108

104109
declare global {
110+
type OnMessageUnsubscribe = () => void;
111+
105112
type TypeOfAppAPI = typeof appAPI;
106113

107114
type AppAPI = {

0 commit comments

Comments
 (0)