useUnit Hook
Using the ActiveJS is similar to RxJS Observables and other observable and subscription-based libraries.
However, if you don't want to create a
useState
and useEffect
binding every time you use a Unit, you can create a custom Hook
for using ActiveJS Units, and pass the Unit to useUnit
Hook to bind the Unit with your React component.TypeScript
JavaScript
import { useState, useEffect } from "react";
import { UnitBase } from "@activejs/core";
const bind = <T extends Function>(method: T, thisArg: any): T =>
method.bind(thisArg)
export type UnitValueType<T> = T extends UnitBase<infer X> ? X : never
export function useUnit<U extends UnitBase<any>>(unit: U) {
type T = UnitValueType<U>
const [value, setValue] = useState<T>()
useEffect(() => {
const subscription = unit.subscribe(setValue);
return () => subscription.unsubscribe();
}, [])
return {
value,
dispatch: bind(unit.dispatch, unit),
resetValue: bind(unit.resetValue, unit)
}
}
import { useState, useEffect } from 'react'
import { UnitBase } from '@activejs/core'
export const useUnit = (unit) => {
const [value, setValue] = useState()
useEffect(() => {
const subscription = unit.subscribe(setValue)
return () => subscription.unsubscribe()
}, []);
const dispatch = v => unit.dispatch(v)
const resetValue = () => unit.resetValue()
return {value, dispatch, resetValue}
}
Last modified 2yr ago