UNPKG

@wener/console

Version:
27 lines (26 loc) 1.05 kB
import { useCallback } from 'react'; import { maybeFunction } from '@wener/utils'; import { useStore } from 'zustand'; import { useShallow } from 'zustand/react/shallow'; export function createViewComponentStateHook(store) { return function(name, selector) { var currentStore = maybeFunction(store); var state = useStore(currentStore, useShallow(function(s) { return selector ? selector(s.components[name] || {}) : s.components[name] || {}; })); return [ state, useCallback(function(action) { currentStore.setState(function(s) { var prevState = s.components[name] || {}; var _action; var nextState = typeof action === 'function' ? (_action = action(prevState)) !== null && _action !== void 0 ? _action : prevState : action; s.components[name] = nextState; }); }, [ currentStore, name ]) ]; }; }