Advertisement
Guest User

Untitled

a guest
Sep 18th, 2019
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.59 KB | None | 0 0
  1. import React from 'react'
  2.  
  3. const noop = () => {}
  4.  
  5. function useScript({ onCreate = noop, onError = noop, onLoad = noop, url }) {
  6. const [isReady, setIsReady] = React.useState(false)
  7.  
  8. React.useEffect(() => {
  9. const script = document.createElement('script')
  10. onCreate()
  11.  
  12. script.src = url
  13. script.async = true
  14. script.onerror = () => {
  15. onError()
  16. }
  17. script.onload = () => {
  18. setIsReady(true)
  19. onLoad()
  20. }
  21.  
  22. document.body.appendChild(script)
  23.  
  24. return () => {
  25. document.body.removeChild(script)
  26. }
  27. }, [onCreate, onError, onLoad, url])
  28.  
  29. return isReady
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement