Skip to content

Commit

Permalink
blitz-rpc: Cleanup Method for Event Listeners (#4173)
Browse files Browse the repository at this point in the history
* feat: logic to cleanup potential memory leak

* styling: add space

* Create poor-crabs-drum.md
  • Loading branch information
siddhsuresh authored Jul 20, 2023
1 parent 0ba2f4e commit df3265b
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/poor-crabs-drum.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"blitz": patch
---

blitz-rpc: Cleanup Event Listeners - Fix potential memory leak by cleaning up any residual event listeners set by blitz.
1 change: 1 addition & 0 deletions packages/blitz/src/global.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ declare global {
beforeHttpRequest: BeforeHttpRequest
beforeHttpResponse: BeforeHttpResponse
}
var __BLITZ_CLEAN_UP_LISTENERS: () => void
}
18 changes: 14 additions & 4 deletions packages/blitz/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,13 +89,23 @@ export function reduceBlitzClientPlugins<TPlugins extends readonly ClientPlugin<
globalThis.__BLITZ_MIDDLEWARE_HOOKS = middleware

if (isClient) {
document.addEventListener("blitz:session-created", async () => {
if (globalThis.__BLITZ_CLEAN_UP_LISTENERS) {
globalThis.__BLITZ_CLEAN_UP_LISTENERS()
}
const onSessionCreated = async () => {
await Promise.all(events.onSessionCreated())
})
document.addEventListener("blitz:rpc-error", async (e) => {
}
const onRpcError = async (e: Event): Promise<void> => {
const customEvent = e as CustomEvent<Error>
await Promise.all(events.onRpcError(customEvent.detail))
})
}
document.addEventListener("blitz:session-created", onSessionCreated)
document.addEventListener("blitz:rpc-error", onRpcError)

globalThis.__BLITZ_CLEAN_UP_LISTENERS = () => {
document.removeEventListener("blitz:session-created", onSessionCreated)
document.removeEventListener("blitz:rpc-error", onRpcError)
}
}

const withPlugins = compose(...providers)
Expand Down

0 comments on commit df3265b

Please sign in to comment.