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
16 changes: 16 additions & 0 deletions src/__tests__/use-script.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -155,4 +155,20 @@ describe('useScript', () => {

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

it('should NOT set loading to true if checkForExisting finds the script', () => {
expect(document.querySelectorAll('script').length).toBe(0);

const previousScript = document.createElement('script');
previousScript.src = 'http://scriptsrc/';
document.body.appendChild(previousScript);

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

const props = { src: 'http://scriptsrc/', checkForExisting: true };
const { result } = renderHook(() => useScript(props));
const [loading] = result.all[0] as Array<any>;
expect(loading).toEqual(false);
expect(document.querySelectorAll('script').length).toBe(1);
});
});
5 changes: 4 additions & 1 deletion src/use-script.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ export default function useScript({
checkForExisting = false,
...attributes
}: ScriptProps): [boolean, ErrorState] {
const [loading, setLoading] = useState(Boolean(src));
const initialLoadingState = checkForExisting ? false : Boolean(src);
const [loading, setLoading] = useState(initialLoadingState);
const [error, setError] = useState<ErrorState>(null);

useEffect(() => {
Expand All @@ -24,6 +25,8 @@ export default function useScript({
if (existing.length > 0) {
setLoading(false);
return;
} else {
setLoading(true);
}
}

Expand Down