Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: useScript #1249

Open
Falci opened this issue May 29, 2020 · 3 comments
Open

Feature request: useScript #1249

Falci opened this issue May 29, 2020 · 3 comments

Comments

@Falci
Copy link

@Falci Falci commented May 29, 2020

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 streamich added this to To do in react-use via automation Jun 3, 2020
@streamich
Copy link
Owner

@streamich streamich commented Jun 3, 2020

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
Copy link

@myamolane myamolane commented Aug 4, 2020

I will do it ~

@myamolane myamolane mentioned this issue Aug 18, 2020
11 of 13 tasks complete
@ctrngk
Copy link

@ctrngk ctrngk commented Nov 11, 2020

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
react-use
  
To do
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
4 participants