streamich / react-use

React Hooks — 👍
http://streamich.github.io/react-use
The Unlicense
41.94k stars 3.16k forks source link

Feature request: useScript #1249

Open Falci opened 4 years ago

Falci commented 4 years ago

Is your feature request related to a problem? Please describe. Problem: I'd like to dynamically import scripts as <script> tags.

Describe the solution you'd like Proposal:

const useScript = ({ url, id, type = 'text/javascript', async = true }) => {
    const [ready, setReady] = React.useState(false);
    const [failed, setFailed] = React.useState(false);

    React.useEffect(() => {
        if (document.getElementById(id)) {
            return;
        }

        const element = document.createElement('script');

        element.src = url;
        element.type = type;
        element.async = async;
        element.id = id;

        setReady(false);
        setFailed(false);

        element.onload = () => setReady(true);

        element.onerror = () => {
            setReady(false);
            setFailed(true);
        };

        document.head.appendChild(element);

        return () => {
            document.head.removeChild(element);
        };
    }, [url, id]);

    return { ready, failed };
};

Describe alternatives you've considered I'm using this the code above directly in my project.

streamich commented 4 years ago

Maybe also on top of that we could build a makeScript helper that defines script at module scope.

const useMyScript = makeScript({ url, id, type, async });

useMyScript.preload();

const Demo = () => {
  const { data, error, isLoading } = useMyScript();
};

.preload() could initiate loading already at module scope.

myamolane commented 4 years ago

I will do it ~

ctrngk commented 4 years ago

For someone who need this feature right now. https://usehooks.com/useScript/