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
7 changes: 1 addition & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 0 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,5 @@
"rimraf": "^3.0.2",
"ts-jest": "^25.3.0",
"typescript": "^3.8.3"
},
"dependencies": {
"react-is-mounted-hook": "^1.0.3"
}
}
47 changes: 44 additions & 3 deletions src/__tests__/use-script.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { renderHook } from '@testing-library/react-hooks';
import { act, renderHook } from '@testing-library/react-hooks';

import useScript from '../use-script';

Expand Down Expand Up @@ -57,10 +57,51 @@ describe('useScript', () => {
it('should render a script only once', () => {
expect(document.querySelectorAll('script').length).toBe(0);

renderHook(() => useScript({ src: 'http://scriptsrc/' }));
const props = { src: 'http://scriptsrc/' };
const handle = renderHook((p) => useScript(p), {
initialProps: props,
});
expect(document.querySelectorAll('script').length).toBe(1);

renderHook(() => useScript({ src: 'http://scriptsrc/' }));
handle.rerender();
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The original test was equivalent to testing two separate components. This test is more akin to how the library is used.

If it was desired to avoid duplicate tags across components, I believe external state would be the correct solution in any case.

expect(document.querySelectorAll('script').length).toBe(1);
});

it('should set loading false on load', async () => {
const props = { src: 'http://scriptsrc/' };
const handle = renderHook((p) => useScript(p), {
initialProps: props,
});

const [loading, error] = handle.result.current;
expect(loading).toBe(true);
expect(error).toBe(null);

act(() => {
const el = document.querySelector('script');
if (el) {
el.dispatchEvent(new Event('load'));
}
});

const [loadingAfter, errorAfter] = handle.result.current;
expect(loadingAfter).toBe(false);
expect(errorAfter).toBe(null);
});

it('should not cause issues on unmount', async () => {
const props = { src: 'http://scriptsrc/' };
const handle = renderHook((p) => useScript(p), {
initialProps: props,
});

handle.unmount();

act(() => {
const el = document.querySelector('script');
if (el) {
el.dispatchEvent(new Event('load'));
}
});
});
});
23 changes: 5 additions & 18 deletions src/use-script.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
import { useState, useEffect } from 'react';
import useIsMounted from 'react-is-mounted-hook';

export interface ScriptProps {
src: HTMLScriptElement['src'];
onload?: HTMLScriptElement['onload'];
onerror?: HTMLScriptElement['onerror'];
[key: string]: any;
}

Expand All @@ -14,20 +11,12 @@ export default function useScript({
src,
...attributes
}: ScriptProps): [boolean, ErrorState] {
const isMounted = useIsMounted();
const [loading, setLoading] = useState(true);
const [error, setError] = useState<ErrorState>(null);

useEffect(() => {
if (!isBrowser) return;

if (document.querySelector(`script[src="${src}"]`)) {
if (isMounted()) {
setLoading(false);
}
return;
}

const scriptEl = document.createElement('script');
scriptEl.setAttribute('src', src);

Expand All @@ -40,14 +29,10 @@ export default function useScript({
});

const handleLoad = () => {
if (isMounted()) {
setLoading(false);
}
setLoading(false);
};
const handleError = (error: ErrorEvent) => {
if (isMounted()) {
setError(error);
}
setError(error);
};

scriptEl.addEventListener('load', handleLoad);
Expand All @@ -59,7 +44,9 @@ export default function useScript({
scriptEl.removeEventListener('load', handleLoad);
scriptEl.removeEventListener('error', handleError);
};
}, [src, attributes, isMounted]);
// we need to ignore the attributes as they're a new object per call, so we'd never skip an effect call
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [src]);

return [loading, error];
}
Expand Down