-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseRedux.ts
48 lines (41 loc) · 1.51 KB
/
useRedux.ts
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
47
48
import type { ChangeEvent } from 'react'
import { useEffect, useRef } from 'react'
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'
import type { AppDispatch, AppState } from '../app/store'
export const useForm =
<TContent>(defaultValues: TContent) =>
(handler: (content: TContent) => void) =>
async (event: ChangeEvent<HTMLFormElement>) => {
event.preventDefault()
event.persist()
const form = event.target as HTMLFormElement
const elements = Array.from(form.elements) as HTMLInputElement[]
const data = elements
.filter((element) => element.hasAttribute('name'))
.reduce(
(object, element) => ({
...object,
[`${element.getAttribute('name')}`]: element.value,
}),
defaultValues
)
await handler(data)
form.reset()
}
// https://overreacted.io/making-setinterval-declarative-with-react-hooks/
export const useInterval = (callback: Function, delay: number) => {
const savedCallback = useRef<Function>()
useEffect(() => {
savedCallback.current = callback
}, [callback])
useEffect(() => {
const handler = (...args: any) => savedCallback.current?.(...args)
if (delay !== null) {
const id = setInterval(handler, delay)
return () => clearInterval(id)
}
}, [delay])
}
// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = () => useDispatch<AppDispatch>()
export const useAppSelector: TypedUseSelectorHook<AppState> = useSelector