From b572c06a70ef116c56521cb9c4b231b6a23c985a Mon Sep 17 00:00:00 2001 From: Dan Green Date: Thu, 2 Sep 2021 13:20:57 -0700 Subject: [PATCH] Changes the behavior of initial loading state. When using the `checkForExisting` option. Resolves #24 --- src/__tests__/use-script.test.tsx | 16 ++++++++++++++++ src/use-script.tsx | 5 ++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/__tests__/use-script.test.tsx b/src/__tests__/use-script.test.tsx index e4de8c8..35c4fd6 100644 --- a/src/__tests__/use-script.test.tsx +++ b/src/__tests__/use-script.test.tsx @@ -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; + expect(loading).toEqual(false); + expect(document.querySelectorAll('script').length).toBe(1); + }); }); diff --git a/src/use-script.tsx b/src/use-script.tsx index 02da5be..1bc5e2b 100644 --- a/src/use-script.tsx +++ b/src/use-script.tsx @@ -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(null); useEffect(() => { @@ -24,6 +25,8 @@ export default function useScript({ if (existing.length > 0) { setLoading(false); return; + } else { + setLoading(true); } }