-
Notifications
You must be signed in to change notification settings - Fork 9
/
useGbaSaveRestoreState.js
42 lines (34 loc) · 1011 Bytes
/
useGbaSaveRestoreState.js
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
import { useContext, useEffect, useState } from 'react'
import { GbaContext } from 'react-gbajs'
const keyCodeQ = 81
const keyCodeW = 87
const keyCodeToAction = ({
[keyCodeQ]: 'save',
[keyCodeW]: 'restore',
})
const useGbaSaveRestoreState = () => {
const [savedState, setSavedState] = useState()
const {
play,
saveState,
} = useContext(GbaContext)
useEffect(() => {
const switchHandle = ({ keyCode }) => {
const action = keyCodeToAction[keyCode]
if (action === 'save') {
setSavedState(saveState())
return
}
if (action === 'restore' && savedState !== undefined) {
play({ restoreState: savedState })
}
}
window.addEventListener('keydown', switchHandle)
window.addEventListener('keyup', switchHandle)
return () => {
window.removeEventListener('keydown', switchHandle)
window.removeEventListener('keyup', switchHandle)
}
}, [savedState, play, saveState])
}
export default useGbaSaveRestoreState