Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions src/EmailEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import React, {
useState,
useImperativeHandle,
useMemo,
useRef,
} from 'react';
import type { DisplayMode, UnlayerEditor } from '@unlayer/types';

Expand Down Expand Up @@ -51,9 +52,14 @@ function EmailEditorInner<TDisplayMode extends DisplayMode | undefined = 'email'
[editor]
);

// Keep a ref to the latest editor so the unmount cleanup below doesn't
// capture the initial (null) state.
const editorRef = useRef(editor);
editorRef.current = editor;

useEffect(() => {
return () => {
editor?.destroy();
editorRef.current?.destroy();
};
}, []);

Expand Down Expand Up @@ -93,7 +99,7 @@ function EmailEditorInner<TDisplayMode extends DisplayMode | undefined = 'email'
onReady(editor);
});
}
}, [editor, Object.keys(methodProps).join(',')]);
}, [editor, methodProps.join(',')]);

return (
<div
Expand Down
23 changes: 23 additions & 0 deletions test/destroy.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import React from 'react';
import { render } from '@testing-library/react';
import Editor from '../src';

jest.mock('../src/loadScript', () => ({
loadScript: (callback: Function) => callback(),
}));

it('destroys the editor on unmount', () => {
const destroy = jest.fn();
(global as any).unlayer = {
createEditor: jest.fn(() => ({
destroy,
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
})),
};

const { unmount } = render(<Editor editorId="destroy-test-editor" />);
unmount();

expect(destroy).toHaveBeenCalledTimes(1);
});
25 changes: 25 additions & 0 deletions test/quickUnmount.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import React from 'react';
import { render, act } from '@testing-library/react';
import Editor from '../src';

let scriptLoadedCallback: Function;
jest.mock('../src/loadScript', () => ({
loadScript: (callback: Function) => {
scriptLoadedCallback = callback;
},
}));

it('does not create the editor when unmounted before the embed script loads', () => {
const createEditor = jest.fn();
(global as any).unlayer = { createEditor };

const { unmount } = render(<Editor editorId="quick-unmount-editor" />);
unmount();

// Embed script finishes loading after the component is gone.
act(() => {
scriptLoadedCallback();
});

expect(createEditor).not.toHaveBeenCalled();
});