-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathuseScript.ts
More file actions
46 lines (39 loc) · 1.17 KB
/
useScript.ts
File metadata and controls
46 lines (39 loc) · 1.17 KB
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
38
39
40
41
42
43
44
45
46
import { useState, useEffect } from 'react'
import { IResponse } from './interface'
export default function useScript(mode: string): boolean[] {
const src =
mode.toLowerCase() === 'test'
? 'https://newwebpay.qa.interswitchng.com/inline-checkout.js'
: 'https://newwebpay.interswitchng.com/inline-checkout.js'
const [state, setState] = useState<IResponse>({
loaded: false,
error: false
})
useEffect(() => {
const script = document.createElement('script')
script.src = src
script.async = true
const onScriptLoad = () => {
setState({
loaded: true,
error: false
})
}
const onScriptError = () => {
setState({
loaded: false,
error: true
})
}
script.addEventListener('load', onScriptLoad)
script.addEventListener('complete', onScriptLoad)
script.addEventListener('error', onScriptError)
document.body.appendChild(script)
return () => {
script.removeEventListener('load', onScriptLoad)
script.removeEventListener('complete', onScriptLoad)
script.removeEventListener('error', onScriptError)
}
}, [src])
return [state.loaded, state.error]
}