UNPKG

subscriber_state

Version:

subscriberState es un hook de react para controlar el estado de tus aplicaciones, basado en suscripciones, suscribiendote a las propiedades del estado.

31 lines (30 loc) 1.04 kB
import { useReducer, useMemo, useCallback } from 'react'; import { Warehouse } from './warehouse.js'; import { v4 as uuidv4 } from 'uuid'; const reducer = (state) => !state; export function useSubscriberState(props, notNotify = false, uuid) { const warehouse = Warehouse.getInstance(); // Get component name //crypto-ramdom-uuid if (!uuid) { uuid = crypto.randomUUID(); } const componentName = useMemo(() => { return `${new Error().stack ?.split('\n')[2] .trim().split(' ')[1]}-${uuid ?? uuidv4()}`; }, [uuid]); const [_, forceUpdate] = useReducer(reducer, false); const subscriber = useCallback(() => { warehouse.setSubscriber({ props: Array.isArray(props) ? props : [props], dispatch: forceUpdate, notNotify }, componentName); }, [props, warehouse, notNotify, componentName]); subscriber(); return [ warehouse.getGlobalStateBySubscriber(componentName), warehouse.actions, ]; }