From 5be934ee58e0902816f2051a75ec96432b364127 Mon Sep 17 00:00:00 2001 From: Jerel Miller Date: Fri, 25 Sep 2020 17:17:51 -0700 Subject: [PATCH] feat: add ability to define onLoad and onError handlers for useScript --- src/hooks/useScript.js | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/src/hooks/useScript.js b/src/hooks/useScript.js index b8de4b3b6..2aa11004c 100644 --- a/src/hooks/useScript.js +++ b/src/hooks/useScript.js @@ -1,11 +1,29 @@ -import { useEffect, useState } from 'react'; +import { useEffect, useState, useRef } from 'react'; import useShallowMemo from './useShallowMemo'; +const noop = () => {}; + const useScript = (src, options) => { - const { attributes = {}, async: isAsync = true, crossOrigin } = options || {}; + const { + attributes = {}, + async: isAsync = true, + crossOrigin, + onLoad = noop, + onError = noop, + } = options || {}; const [loaded, setLoaded] = useState(false); - const [error, setError] = useState(null); + const [error, setError] = useState(false); const attrs = useShallowMemo(() => attributes, [attributes]); + const onLoadHandler = useRef(); + const onErrorHandler = useRef(); + + useEffect(() => { + onLoadHandler.current = onLoad; + }, [onLoad]); + + useEffect(() => { + onErrorHandler.current = onError; + }, [onError]); useEffect(() => { const script = window.document.createElement('script'); @@ -14,8 +32,14 @@ const useScript = (src, options) => { script.crossOrigin = crossOrigin; script.onload = () => { setLoaded(true); + onLoadHandler.current(); + }; + + script.onerror = () => { + setError(true); + onErrorHandler.current(); }; - script.onerror = setError; + script.src = src; Object.entries(attrs).forEach(([attribute, value]) =>