Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

fix: cleanup anywidget on unmount (#4236)

Myles Scolnicka17122f8afb0
diff --git a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
index bdf155f17b..969add39ea 100644
--- a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
+++ b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
@@ -155,7 +155,7 @@ async function runAnyWidgetModule(
widgetDef: AnyWidget,
model: Model<T>,
el: HTMLElement,
-) {
+): Promise<() => void> {
const experimental: Experimental = {
invoke: async (name, msg, options) => {
const message =
@@ -169,7 +169,10 @@ async function runAnyWidgetModule(
const widget =
typeof widgetDef === "function" ? await widgetDef() : widgetDef;
await widget.initialize?.({ model, experimental });
- await widget.render?.({ model, el, experimental });
+ const unsub = await widget.render?.({ model, el, experimental });
+ return () => {
+ unsub?.();
+ };
}
function isAnyWidgetModule(mod: any): mod is { default: AnyWidget } {
@@ -220,7 +223,14 @@ const LoadedSlot = ({
if (!htmlRef.current) {
return;
}
- runAnyWidgetModule(widget, model.current, htmlRef.current);
+ const unsubPromise = runAnyWidgetModule(
+ widget,
+ model.current,
+ htmlRef.current,
+ );
+ return () => {
+ unsubPromise.then((unsub) => unsub());
+ };
// We re-run the widget when the jsUrl changes, which means the cell
// that created the Widget has been re-run.
// We need to re-run the widget because it may contain initialization code