MCPcopy Create free account
hub / github.com/effector/effector / useUnitBase

Function useUnitBase

src/react/apiBase.ts:46–176  ·  view source on GitHub ↗
(
  shape: Shape | {'@@unitShape': () => Shape},
  scope?: Scope,
)

Source from the content-addressed store, hash-verified

44}
45
46export function useUnitBase<Shape extends {[key: string]: Unit<any>}>(
47 shape: Shape | {'@@unitShape': () => Shape},
48 scope?: Scope,
49) {
50 const isSingleUnit = is.unit(shape)
51 let normShape: {[key: string]: Unit<any>} = {}
52 if (isSingleUnit) {
53 normShape = {unit: shape}
54 } else if ('@@unitShape' in shape) {
55 if (typeof shape['@@unitShape'] === 'function') {
56 normShape = shape['@@unitShape']()
57 } else {
58 throwError('expect @@unitShape to be a function')
59 }
60 } else {
61 normShape = shape
62 }
63 const isList = Array.isArray(normShape)
64 const flagsRef = React.useRef({
65 stale: true,
66 justSubscribed: false,
67 scope,
68 })
69 const [eventsShape, storeKeys, storeValues, eventKeys, eventValues] =
70 React.useMemo(() => {
71 flagsRef.current.stale = true
72 const shape = Array.isArray(normShape) ? [] : ({} as any)
73 const storeKeys: string[] = []
74 const storeValues: Array<Store<any>> = []
75 const eventKeys: string[] = []
76 const eventValues: Array<Unit<any>> = []
77 for (const key in normShape) {
78 if (!Object.prototype.hasOwnProperty.call(normShape, key)) continue
79 const unit = normShape[key]
80 if (!is.unit(unit)) {
81 const keyMessage = isSingleUnit ? 'argument' : `value in key "${key}"`
82 throwError(`expect useUnit ${keyMessage} to be a unit`)
83 }
84 if (is.event(unit) || is.effect(unit)) {
85 shape[key] = scope ? scopeBind(unit as Event<any>, {scope}) : unit
86 eventKeys.push(key)
87 eventValues.push(unit)
88 } else {
89 shape[key] = null
90 storeKeys.push(key)
91 storeValues.push(unit as Store<any>)
92 }
93 }
94 return [shape, storeKeys, storeValues, eventKeys, eventValues]
95 }, [
96 flagsRef,
97 scope,
98 ...Object.keys(normShape),
99 ...Object.values(normShape),
100 ])
101 const stateRef = React.useRef({
102 value: eventsShape,
103 storeKeys,

Callers 4

useUnitFunction · 0.90
useUnitFunction · 0.90
useListBaseFunction · 0.70
useGateBaseFunction · 0.70

Calls 6

throwErrorFunction · 0.90
scopeBindFunction · 0.90
createWatchFunction · 0.90
eventMethod · 0.80
effectMethod · 0.80
stateReaderFunction · 0.70

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…