23 lines
753 B
TypeScript
23 lines
753 B
TypeScript
import { useCallback, useEffect, useState } from 'react'
|
|
import KetchupClient from 'ketchup-client'
|
|
|
|
type Dispatch<Action> = (action: Action, timestamp?: number) => void
|
|
|
|
export default function useKetchup<State, Action>(
|
|
url: string,
|
|
reducer: (state: State, action: Action) => State,
|
|
): [State | undefined, Dispatch<Action>] {
|
|
const [proj, setProj] = useState<State>()
|
|
const [kc, setKc] = useState<KetchupClient<State, Action>>()
|
|
|
|
useEffect(() => {
|
|
const newKc = new KetchupClient(url, reducer)
|
|
setKc(newKc)
|
|
newKc.on('projection', setProj)
|
|
return () => { newKc.off('projection', setProj) }
|
|
}, [url, reducer])
|
|
|
|
const dispatch = useCallback((a, ts) => kc?.dispatch(a, ts), [kc])
|
|
return [proj, dispatch, /* connected */]
|
|
}
|