-
Notifications
You must be signed in to change notification settings - Fork 516
Expand file tree
/
Copy pathuseScript.ts
More file actions
37 lines (29 loc) · 791 Bytes
/
useScript.ts
File metadata and controls
37 lines (29 loc) · 791 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { useEffect, useState } from 'react'
type ScriptState = {
ready: boolean
error: boolean
}
export const useScript = (url: string): ScriptState => {
const [state, setState] = useState<ScriptState>({
error: false,
ready: false,
})
useEffect(() => {
const existing = document.querySelector(`script[src="${url}"]`)
if (existing) {
setState({ error: false, ready: true })
return
}
const script = document.createElement('script')
script.src = url
script.async = true
script.addEventListener('load', () => {
setState({ error: false, ready: true })
})
script.addEventListener('error', () => {
setState({ error: true, ready: false })
})
document.head.appendChild(script)
}, [url])
return state
}