Skip to content

Commit

Permalink
feat: add ability to define onLoad and onError handlers for useScript
Browse files Browse the repository at this point in the history
  • Loading branch information
jerelmiller committed Sep 26, 2020
1 parent 28aa1d2 commit 5be934e
Showing 1 changed file with 28 additions and 4 deletions.
32 changes: 28 additions & 4 deletions src/hooks/useScript.js
Original file line number Diff line number Diff line change
@@ -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');
Expand All @@ -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]) =>
Expand Down

0 comments on commit 5be934e

Please sign in to comment.