Skip to content
Merged
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
22 changes: 22 additions & 0 deletions src/react-script-hook/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -272,4 +272,26 @@ describe('useScript', () => {
expect(document.querySelectorAll('script').length).toBe(1);
});
});

it('should remove script from DOM and scripts cache when unmounted during loading', () => {
expect(document.querySelectorAll('script').length).toBe(0);
expect(Object.keys(scripts).length).toBe(0);

const testSrc = 'http://scriptsrc/test';
const { unmount } = renderHook(() => useScript({ src: testSrc }));

// Verify script was added
expect(document.querySelectorAll('script').length).toBe(1);
expect(Object.keys(scripts).length).toBe(1);
expect(scripts[testSrc]).toBeDefined();
expect(scripts[testSrc].loading).toBe(true);

// Unmount the component while script is still loading (before load event)
unmount();

// Verify script was removed from DOM and cache
expect(document.querySelectorAll('script').length).toBe(0);
expect(Object.keys(scripts).length).toBe(0);
expect(scripts[testSrc]).toBeUndefined();
});
});
2 changes: 1 addition & 1 deletion src/react-script-hook/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ export default function useScript({
// but only applied when loading
if (status && status.loading) {
scriptEl.remove();
delete exports.scripts[src];
delete scripts[src];
}
};
// we need to ignore the attributes as they're a new object per call, so we'd never skip an effect call
Expand Down