@wwog/react 1.2.8 → 1.2.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +45 -0
- package/dist/index.d.mts +74 -8
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/src/index.ts +5 -7
- package/src/utils/createExternalState.ts +107 -0
- package/src/utils/index.ts +4 -0
package/README.md
CHANGED
|
@@ -367,6 +367,51 @@ You can also use a container wrapper element:
|
|
|
367
367
|
|
|
368
368
|
> Internal functions used by some components, which can also be used if needed
|
|
369
369
|
|
|
370
|
+
#### `createExternalState` (v1.2.9+)
|
|
371
|
+
|
|
372
|
+
A lightweight external state management utility that allows you to create and manage state outside the React component tree while maintaining perfect integration with components.
|
|
373
|
+
|
|
374
|
+
```tsx
|
|
375
|
+
import { createExternalState } from "@wwog/react";
|
|
376
|
+
|
|
377
|
+
// Create a global theme state
|
|
378
|
+
const themeState = createExternalState('light', (newTheme, oldTheme) => {
|
|
379
|
+
console.log(`Theme changed from ${oldTheme} to ${newTheme}`);
|
|
380
|
+
});
|
|
381
|
+
|
|
382
|
+
// Get or modify state from anywhere
|
|
383
|
+
console.log(themeState.get()); // 'light'
|
|
384
|
+
themeState.set('dark');
|
|
385
|
+
|
|
386
|
+
// Use the state in components
|
|
387
|
+
function ThemeConsumer() {
|
|
388
|
+
const [theme, setTheme] = themeState.use();
|
|
389
|
+
|
|
390
|
+
return (
|
|
391
|
+
<div className={theme}>
|
|
392
|
+
Current theme: {theme}
|
|
393
|
+
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
|
|
394
|
+
Toggle theme
|
|
395
|
+
</button>
|
|
396
|
+
</div>
|
|
397
|
+
);
|
|
398
|
+
}
|
|
399
|
+
```
|
|
400
|
+
|
|
401
|
+
- `createExternalState<T>(initialState, sideEffect?)`: Creates a state accessible outside components
|
|
402
|
+
- `initialState`: Initial state value
|
|
403
|
+
- `sideEffect`: Optional side effect function, called on state updates
|
|
404
|
+
- Returns an object with methods:
|
|
405
|
+
- `get()`: Get the current state value
|
|
406
|
+
- `set(newState)`: Update the state value
|
|
407
|
+
- `use()`: React Hook, returns `[state, setState]` for using this state in components
|
|
408
|
+
|
|
409
|
+
Use cases:
|
|
410
|
+
- Global state management (themes, user settings, etc.)
|
|
411
|
+
- Cross-component communication
|
|
412
|
+
- Reactive state in services or utility classes
|
|
413
|
+
- Sharing state with non-React code
|
|
414
|
+
|
|
370
415
|
#### `formatDate`
|
|
371
416
|
|
|
372
417
|
A relatively standard date formatting function
|
package/dist/index.d.mts
CHANGED
|
@@ -449,6 +449,78 @@ interface UseControlledOptions<T> {
|
|
|
449
449
|
}
|
|
450
450
|
declare function useControlled<T>(options: UseControlledOptions<T>): [T, Dispatch<React.SetStateAction<T>>];
|
|
451
451
|
|
|
452
|
+
/**
|
|
453
|
+
* @en Callback function type for state change listeners
|
|
454
|
+
* @zh 状态变更监听器的回调函数类型
|
|
455
|
+
* @template T The type of the state / 状态的类型
|
|
456
|
+
*/
|
|
457
|
+
type CreateStateListener<T> = (state: T) => void;
|
|
458
|
+
/**
|
|
459
|
+
* @zh 如果需要在变更状态时执行副作用,可以传入函数,对于异步函数,会在更改状态后执行,不会阻塞状态更新, 尽可能在外部使用useEffect处理异步副作用
|
|
460
|
+
* @en If you need to perform side effects when changing the state, you can pass a function. For asynchronous functions, it will be executed after the state changes without blocking the state update, so it's best to use useEffect for handling asynchronous side effects.
|
|
461
|
+
* @template T The type of the state / 状态的类型
|
|
462
|
+
* @param newState The new state value / 新的状态值
|
|
463
|
+
* @param prevState The previous state value / 之前的状态值
|
|
464
|
+
*/
|
|
465
|
+
type ExternalSideEffect<T> = (newState: T, prevState: T) => void | Promise<void>;
|
|
466
|
+
/**
|
|
467
|
+
* @en External state management interface
|
|
468
|
+
* @zh 外部状态管理接口
|
|
469
|
+
* @template T The type of the state / 状态的类型
|
|
470
|
+
*/
|
|
471
|
+
interface ExternalState<T> {
|
|
472
|
+
/**
|
|
473
|
+
* @en Get the current state value
|
|
474
|
+
* @zh 获取当前状态值
|
|
475
|
+
* @returns The current state value / 当前状态值
|
|
476
|
+
*/
|
|
477
|
+
get: () => T;
|
|
478
|
+
/**
|
|
479
|
+
* @en Set a new state value
|
|
480
|
+
* @zh 设置新的状态值
|
|
481
|
+
* @param newState The new state value / 新的状态值
|
|
482
|
+
*/
|
|
483
|
+
set: (newState: T) => void;
|
|
484
|
+
/**
|
|
485
|
+
* @en React Hook for using external state in components
|
|
486
|
+
* @zh 在组件中使用外部状态的 React Hook
|
|
487
|
+
* @returns Array containing current state and update function, similar to useState / 包含当前状态和更新函数的数组,类似于 useState
|
|
488
|
+
*/
|
|
489
|
+
use: () => [T, (newState: T) => void];
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
492
|
+
*
|
|
493
|
+
* @example
|
|
494
|
+
* ```tsx
|
|
495
|
+
* // Create an app-level theme state
|
|
496
|
+
* const themeState = createExternalState('light');
|
|
497
|
+
*
|
|
498
|
+
* // Get or modify state outside components
|
|
499
|
+
* console.log(themeState.get()); // 'light'
|
|
500
|
+
* themeState.set('dark');
|
|
501
|
+
*
|
|
502
|
+
* // Use state in components
|
|
503
|
+
* function ThemeConsumer() {
|
|
504
|
+
* const [theme, setTheme] = themeState.use();
|
|
505
|
+
*
|
|
506
|
+
* return (
|
|
507
|
+
* <div className={theme}>
|
|
508
|
+
* <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
|
|
509
|
+
* Toggle theme / 切换主题
|
|
510
|
+
* </button>
|
|
511
|
+
* </div>
|
|
512
|
+
* );
|
|
513
|
+
* }
|
|
514
|
+
* ```
|
|
515
|
+
*/
|
|
516
|
+
declare function createExternalState<T>(initialState: T, sideEffect?: ExternalSideEffect<T>): ExternalState<T>;
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* @description 性能优化,替代 React.Children.forEach, 回调可以返回 false 来中断循环
|
|
520
|
+
* @description_en Replace React.Children.forEach, the callback can return false to interrupt the loop
|
|
521
|
+
*/
|
|
522
|
+
declare function childrenLoop(children: React$1.ReactNode | undefined, callback: (child: React$1.ReactNode, index: number) => boolean | void): void;
|
|
523
|
+
|
|
452
524
|
/**
|
|
453
525
|
* @param schema
|
|
454
526
|
* @example
|
|
@@ -488,11 +560,5 @@ declare class Counter {
|
|
|
488
560
|
next(): number;
|
|
489
561
|
}
|
|
490
562
|
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
* @description_en Replace React.Children.forEach, the callback can return false to interrupt the loop
|
|
494
|
-
*/
|
|
495
|
-
declare function childrenLoop(children: React$1.ReactNode | undefined, callback: (child: React$1.ReactNode, index: number) => boolean | void): void;
|
|
496
|
-
|
|
497
|
-
export { ArrayRender, Counter, DateRender, False, If, Pipe, Scope, SizeBox, Styles, Switch, Toggle, True, When, childrenLoop, cx, formatDate, useControlled };
|
|
498
|
-
export type { ArrayRenderProps, CxInput, DateRenderProps, ElseIfProps, ElseProps, FalseProps, IfProps, PipeProps, ScopeProps, StylesDescriptor, StylesProps, StylesType, SwitchCaseProps, SwitchDefaultProps, SwitchProps, ThenProps, ToggleProps, TrueProps, UseControlledOptions, WhenProps };
|
|
563
|
+
export { ArrayRender, Counter, DateRender, False, If, Pipe, Scope, SizeBox, Styles, Switch, Toggle, True, When, childrenLoop, createExternalState, cx, formatDate, useControlled };
|
|
564
|
+
export type { ArrayRenderProps, CreateStateListener, CxInput, DateRenderProps, ElseIfProps, ElseProps, ExternalSideEffect, ExternalState, FalseProps, IfProps, PipeProps, ScopeProps, StylesDescriptor, StylesProps, StylesType, SwitchCaseProps, SwitchDefaultProps, SwitchProps, ThenProps, ToggleProps, TrueProps, UseControlledOptions, WhenProps };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import r,{useMemo as h,Children as J,Fragment as S,isValidElement as P,cloneElement as R,useEffect as W,useState as I,useCallback as H}from"react";function T(e,n){if(e===void 0)return;let t=0;if(Array.isArray(e)){for(const l of e)if(n(l,t++)===!1)break}else n(e,t)}const _=(e,n)=>e===n,E=e=>r.createElement(r.Fragment,null,e.children);E.displayName="Switch_Case";const w=e=>r.createElement(r.Fragment,null,e.children);w.displayName="Switch_Default";const y=e=>{const{value:n,compare:t=_,children:l,strict:
|
|
1
|
+
import r,{useMemo as h,Children as J,Fragment as S,isValidElement as P,cloneElement as R,useEffect as W,useState as I,useCallback as H}from"react";function T(e,n){if(e===void 0)return;let t=0;if(Array.isArray(e)){for(const l of e)if(n(l,t++)===!1)break}else n(e,t)}const _=(e,n)=>e===n,E=e=>r.createElement(r.Fragment,null,e.children);E.displayName="Switch_Case";const w=e=>r.createElement(r.Fragment,null,e.children);w.displayName="Switch_Default";const y=e=>{const{value:n,compare:t=_,children:l,strict:o=!1}=e,a=new Set;let s=null,c=null,i=!1;return T(l,(d,u)=>{if(!r.isValidElement(d))throw new Error(`Switch Children only accepts valid React elements at index ${u}`);const m=d.type;if(m.displayName===E.displayName){const f=d.props;if(a.has(f.value))throw new Error(`Switch found duplicate Case value at index ${u}: ${JSON.stringify(f.value)}${o?" (detected in strict mode)":""}`);if(a.add(f.value),!s&&t(n,f.value)&&(s=f.children,o===!1))return!1}else if(m.displayName===w.displayName){if(i)throw new Error(`Switch can only have one Default child at index ${u}`);if(i=!0,c=d.props.children,!o&&s)return!1}else throw new Error(`Switch Children only accepts 'Case' or 'Default' elements, found: ${String(m.displayName||m.name||m)} at index ${u}`)}),r.createElement(r.Fragment,null,s??c)};y.displayName="Switch",y.Case=E,y.Default=w,y.createTyped=function(){return{Switch:y,Case:E,Default:w}};const N=e=>r.createElement(r.Fragment,null,e.children),v=({children:e})=>r.createElement(r.Fragment,null,e),F=e=>r.createElement(r.Fragment,null,e.children);N.displayName="If_Then",v.displayName="If_Else",F.displayName="If_ElseIf";const p=({condition:e,children:n})=>{let t=null,l=null;const o=[];if(r.Children.forEach(n,a=>{if(!r.isValidElement(a))throw new Error("If component only accepts valid React elements");const s=a.type;if(s.displayName===N.displayName){if(t)throw new Error("If component can only have one Then child");t=a}else if(s.displayName===F.displayName)o.push(a);else if(s.displayName===v.displayName){if(l)throw new Error("If component can only have one Else child");l=a}else throw new Error(`If component only accepts 'Then', 'ElseIf', or 'Else' elements as children, found: ${String(s.displayName||s.name||s)}`)}),e)return t?r.createElement(r.Fragment,null,t.props.children):null;for(const a of o)if(a.props.condition)return r.createElement(r.Fragment,null,a.props.children);return l?r.createElement(r.Fragment,null,l.props.children):null};p.displayName="If",p.Then=N,p.ElseIf=F,p.Else=v,p.createTyped=function(){return{If:p,Then:N,ElseIf:F,Else:v}};const B=({condition:e,children:n})=>e?r.createElement(r.Fragment,null,n):null,V=({condition:e,children:n})=>e===!1?r.createElement(r.Fragment,null,n):null,Z=({all:e,any:n,none:t,children:l,fallback:o})=>h(()=>(e&&(n||t)&&console.warn('When: Multiple condition types (all, any, none) provided; "all" takes precedence.'),!!(e&&e.length>0&&e.every(Boolean)||n&&n.length>0&&n.some(Boolean)||t&&t.length>0&&t.every(a=>!a))),[e,n,t])?r.createElement(r.Fragment,null,l):r.createElement(r.Fragment,null,o||null),z=({data:e,transform:n,render:t,fallback:l})=>{const o=h(()=>n.reduce((a,s)=>s(a),e),[e,n]);return o==null?r.createElement(r.Fragment,null,l||null):r.createElement(r.Fragment,null,t(o))},L=e=>{const{children:n,h:t,w:l,size:o,height:a,width:s,className:c}=e;return r.createElement("div",{style:{width:o||l||s,height:o||t||a,flexShrink:0},className:c},n)},q=({let:e,props:n,children:t,fallback:l})=>{const o=h(()=>typeof e=="function"?e(n):e,[e,n]);return!t||!Object.keys(o).length?r.createElement(r.Fragment,null,l||null):r.createElement(r.Fragment,null,t(o))};function M(...e){const n=new Set;for(const t of e)if(t){if(typeof t=="string")n.add(t);else if(Array.isArray(t))t.forEach(l=>n.add(l));else if(typeof t=="object")for(const[l,o]of Object.entries(t))o&&n.add(l)}return Array.from(n).join(" ")}const G=e=>typeof e=="object"&&!!e,b=({className:e,children:n,asWrapper:t=!1})=>{if(!n)return null;if(J.count(n)>1)return console.error("<Styles>: children has more than one child. Please check your code."),r.createElement(S,null,n);if(!e)return r.createElement(S,null,n);const l=typeof e=="string"?e:M(...Object.values(e));if(t)return r.createElement(t===!0?"div":t,{className:l},n);if(P(n)){const o=n;let a=o?.props?.className;return o?.type?.displayName===b.displayName&&G(a)&&(a=M(...Object.values(a))),R(n,{className:M(l,a)})}return console.error("<Styles>: children is not a valid React element. Please check your code."),r.createElement(S,null,n)};b.displayName="W/Styles";const K=e=>{const{index:n=0,options:t,next:l,render:o}=e;W(()=>{if(t.length<n+1)throw new Error(`Index ${n} is out of bounds for options array of length ${t.length}. Defaulting to first option.`)},[n,t]);const[a,s]=I(n),c=()=>{s(i=>t.length?l?l(i,t):(i+1)%t.length:i)};return o(t[a],c)};function Q(e){const{items:n,renderItem:t,filter:l}=e;return n?r.createElement(S,null,n.map((o,a)=>l&&!l(o)?null:t(o,a))):(console.error("ArrayRender: items is null"),null)}function U({source:e,format:n,children:t}){const l=h(()=>{if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){const a=new Date(e);return isNaN(a.getTime())?null:a}return null},[e]),o=h(()=>l?n?n(l):l.toLocaleString():null,[l,n]);return!o||!t?null:r.createElement(r.Fragment,null,t(o))}const X="onChange",$="value";function ee(e){const{defaultValue:n,onBeforeChange:t,trigger:l=X,valuePropName:o=$,props:a}=e,s=Object.prototype.hasOwnProperty.call(a,o),[c,i]=I(n),d=s?a[o]:c,u=h(()=>a[l],[a,l]),m=H(f=>{const g=typeof f=="function"?f(d):f;t&&t(g,d)===!1||(s||i(g),u&&u(g))},[s,t,d,u]);return[d,m]}function te(e,n){let t=e;const l=[],o=()=>t,a=s=>{const c=t;t=s,n&&n(s,c),l.forEach(i=>i(t))};return{get:o,set:a,use:()=>{const[s,c]=r.useState(t);return r.useEffect(()=>(l.push(c),()=>{const i=l.indexOf(c);i>-1&&l.splice(i,1)}),[]),[s,a]}}}function ne(e,n){const t=n||new Date,l=t.getFullYear(),o=t.getMonth()+1,a=t.getDate(),s=t.getHours(),c=t.getMinutes(),i=t.getSeconds(),d=t.getMilliseconds(),u=t.getDay(),m=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],f=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],g=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],x=["January","February","March","April","May","June","July","August","September","October","November","December"],A=f[u],D=m[u],C=o-1,Y=x[C],k=g[C],O={YY:l.toString().slice(2),YYYY:l.toString(),M:o.toString(),MM:o.toString().padStart(2,"0"),MMM:k,MMMM:Y,D:a.toString(),DD:a.toString().padStart(2,"0"),d:u.toString(),dd:D,ddd:D,dddd:A,H:s.toString(),HH:s.toString().padStart(2,"0"),h:(s%12).toString(),hh:(s%12).toString().padStart(2,"0"),m:c.toString(),mm:c.toString().padStart(2,"0"),s:i.toString(),ss:i.toString().padStart(2,"0"),SSS:d.toString().padStart(3,"0"),Z:"+08:00",ZZ:"+0800",A:s<12?"AM":"PM",a:s<12?"am":"pm"};return e.replace(/YYYY|YY|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|m{1,2}|s{1,2}|SSS|Z{1,2}|A|a/g,j=>O[j])}class re{count=0;next(){return this.count++}}export{Q as ArrayRender,re as Counter,U as DateRender,V as False,p as If,z as Pipe,q as Scope,L as SizeBox,b as Styles,y as Switch,K as Toggle,B as True,Z as When,T as childrenLoop,te as createExternalState,M as cx,ne as formatDate,ee as useControlled};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wwog/react",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.9",
|
|
4
4
|
"description": "A practical React component library providing declarative flow control and common UI utility components to make your React code more concise and readable.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"react",
|
package/src/index.ts
CHANGED
|
@@ -1,9 +1,7 @@
|
|
|
1
|
-
export * from
|
|
2
|
-
export * from
|
|
3
|
-
export * from
|
|
1
|
+
export * from "./components/ProcessControl";
|
|
2
|
+
export * from "./components/Sundry";
|
|
3
|
+
export * from "./components/Struct";
|
|
4
4
|
|
|
5
|
-
export * from
|
|
5
|
+
export * from "./hooks";
|
|
6
6
|
|
|
7
|
-
export * from
|
|
8
|
-
export * from './utils/cx'
|
|
9
|
-
export * from './utils/reactUtils'
|
|
7
|
+
export * from "./utils";
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import React from "react";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @en Callback function type for state change listeners
|
|
5
|
+
* @zh 状态变更监听器的回调函数类型
|
|
6
|
+
* @template T The type of the state / 状态的类型
|
|
7
|
+
*/
|
|
8
|
+
export type CreateStateListener<T> = (state: T) => void;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @zh 如果需要在变更状态时执行副作用,可以传入函数,对于异步函数,会在更改状态后执行,不会阻塞状态更新, 尽可能在外部使用useEffect处理异步副作用
|
|
12
|
+
* @en If you need to perform side effects when changing the state, you can pass a function. For asynchronous functions, it will be executed after the state changes without blocking the state update, so it's best to use useEffect for handling asynchronous side effects.
|
|
13
|
+
* @template T The type of the state / 状态的类型
|
|
14
|
+
* @param newState The new state value / 新的状态值
|
|
15
|
+
* @param prevState The previous state value / 之前的状态值
|
|
16
|
+
*/
|
|
17
|
+
export type ExternalSideEffect<T> = (newState: T, prevState: T) => void | Promise<void>;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @en External state management interface
|
|
21
|
+
* @zh 外部状态管理接口
|
|
22
|
+
* @template T The type of the state / 状态的类型
|
|
23
|
+
*/
|
|
24
|
+
export interface ExternalState<T> {
|
|
25
|
+
/**
|
|
26
|
+
* @en Get the current state value
|
|
27
|
+
* @zh 获取当前状态值
|
|
28
|
+
* @returns The current state value / 当前状态值
|
|
29
|
+
*/
|
|
30
|
+
get: () => T;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* @en Set a new state value
|
|
34
|
+
* @zh 设置新的状态值
|
|
35
|
+
* @param newState The new state value / 新的状态值
|
|
36
|
+
*/
|
|
37
|
+
set: (newState: T) => void;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* @en React Hook for using external state in components
|
|
41
|
+
* @zh 在组件中使用外部状态的 React Hook
|
|
42
|
+
* @returns Array containing current state and update function, similar to useState / 包含当前状态和更新函数的数组,类似于 useState
|
|
43
|
+
*/
|
|
44
|
+
use: () => [T, (newState: T) => void];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
*
|
|
49
|
+
* @example
|
|
50
|
+
* ```tsx
|
|
51
|
+
* // Create an app-level theme state
|
|
52
|
+
* const themeState = createExternalState('light');
|
|
53
|
+
*
|
|
54
|
+
* // Get or modify state outside components
|
|
55
|
+
* console.log(themeState.get()); // 'light'
|
|
56
|
+
* themeState.set('dark');
|
|
57
|
+
*
|
|
58
|
+
* // Use state in components
|
|
59
|
+
* function ThemeConsumer() {
|
|
60
|
+
* const [theme, setTheme] = themeState.use();
|
|
61
|
+
*
|
|
62
|
+
* return (
|
|
63
|
+
* <div className={theme}>
|
|
64
|
+
* <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
|
|
65
|
+
* Toggle theme / 切换主题
|
|
66
|
+
* </button>
|
|
67
|
+
* </div>
|
|
68
|
+
* );
|
|
69
|
+
* }
|
|
70
|
+
* ```
|
|
71
|
+
*/
|
|
72
|
+
export function createExternalState<T>(
|
|
73
|
+
initialState: T,
|
|
74
|
+
sideEffect?: ExternalSideEffect<T>
|
|
75
|
+
): ExternalState<T> {
|
|
76
|
+
let state: T = initialState;
|
|
77
|
+
const listeners: CreateStateListener<T>[] = [];
|
|
78
|
+
|
|
79
|
+
const get = () => state;
|
|
80
|
+
|
|
81
|
+
const set = (newState: T) => {
|
|
82
|
+
const prevState = state;
|
|
83
|
+
state = newState;
|
|
84
|
+
if (sideEffect) {
|
|
85
|
+
sideEffect(newState, prevState);
|
|
86
|
+
}
|
|
87
|
+
listeners.forEach((listener) => listener(state));
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const use = () => {
|
|
91
|
+
const [localState, setLocalState] = React.useState(state);
|
|
92
|
+
|
|
93
|
+
React.useEffect(() => {
|
|
94
|
+
listeners.push(setLocalState);
|
|
95
|
+
return () => {
|
|
96
|
+
const index = listeners.indexOf(setLocalState);
|
|
97
|
+
if (index > -1) {
|
|
98
|
+
listeners.splice(index, 1);
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
}, []);
|
|
102
|
+
|
|
103
|
+
return [localState, set] as [T, (newState: T) => void];
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
return { get, set, use };
|
|
107
|
+
}
|