react-hooks-global-states 10.2.0 β†’ 11.0.0-beta.2

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/GlobalStore.d.ts CHANGED
@@ -1,15 +1,26 @@
1
- import type { ActionCollectionConfig, StateSetter, GlobalStoreCallbacks, ActionCollectionResult, MetadataSetter, StateGetter, SubscriberParameters, MetadataGetter, StateHook, BaseMetadata, StateChanges, StoreTools, ObservableFragment } from './types';
1
+ import type { ActionCollectionConfig, GlobalStoreCallbacks, ActionCollectionResult, MetadataSetter, SubscribeCallbackConfig, SubscribeCallback, SelectorCallback, SubscriberParameters, StateHook, BaseMetadata, StateChanges, StoreTools, ObservableFragment, UnsubscribeCallback, AnyFunction } from './types';
2
2
  /**
3
3
  * The GlobalStore class is the main class of the library and it is used to create a GlobalStore instances
4
4
  * */
5
- export declare class GlobalStore<State, Metadata extends BaseMetadata | unknown, ActionsConfig extends ActionCollectionConfig<State, Metadata> | undefined | unknown, PublicStateMutator = keyof ActionsConfig extends never | undefined ? StateSetter<State> : ActionCollectionResult<State, Metadata, NonNullable<ActionsConfig>>> {
5
+ export declare class GlobalStore<State, Metadata extends BaseMetadata, ActionsConfig extends ActionCollectionConfig<State, Metadata> | undefined | unknown, PublicStateMutator = keyof ActionsConfig extends never | undefined ? React.Dispatch<React.SetStateAction<State>> : ActionCollectionResult<State, Metadata, NonNullable<ActionsConfig>>, StateDispatch = React.Dispatch<React.SetStateAction<State>>> {
6
6
  protected _name: string;
7
- protected wasDisposed: boolean;
8
7
  actionsConfig: ActionsConfig | null;
9
8
  callbacks: GlobalStoreCallbacks<State, Metadata> | null;
10
9
  metadata: Metadata;
11
- actions: ActionCollectionResult<State, Metadata, NonNullable<ActionsConfig>> | null;
12
- subscribers: Map<string, SubscriberParameters>;
10
+ /**
11
+ * @description If the actionsConfig is defined, this will be a map of actions that can be used to modify or interact with the state
12
+ * */
13
+ actions: PublicStateMutator extends AnyFunction ? null : PublicStateMutator;
14
+ /**
15
+ * @description The main hook that will be used to interact with the global state
16
+ */
17
+ use: StateHook<State, StateDispatch, PublicStateMutator, Metadata>;
18
+ /**
19
+ * @description
20
+ * Access to the store api that will be passed to the actions and callbacks
21
+ */
22
+ private configurationCallbackParam;
23
+ subscribers: Set<SubscriberParameters>;
13
24
  state: State;
14
25
  constructor(state: State);
15
26
  constructor(state: State, args: {
@@ -22,7 +33,15 @@ export declare class GlobalStore<State, Metadata extends BaseMetadata | unknown,
22
33
  protected onStateChanged?: (args: StoreTools<State, Metadata> & StateChanges<State>) => void;
23
34
  protected onSubscribed?: (args: StoreTools<State, Metadata>, subscription: SubscriberParameters) => void;
24
35
  protected computePreventStateChange?: (parameters: StoreTools<State, Metadata> & StateChanges<State>) => boolean;
36
+ /**
37
+ * @description
38
+ * Initializes the global store, setting up the main hook and actions map if applicable,
39
+ */
25
40
  protected initialize: () => Promise<void>;
41
+ /**
42
+ * set the state for a single subscriber
43
+ * validate if the state should be updated by comparing the previous state and the new state
44
+ */
26
45
  protected executeSetStateForSubscriber: (subscription: SubscriberParameters, args: {
27
46
  forceUpdate: boolean | undefined;
28
47
  newState: State;
@@ -33,9 +52,12 @@ export declare class GlobalStore<State, Metadata extends BaseMetadata | unknown,
33
52
  };
34
53
  /**
35
54
  * set the state and update all the subscribers
36
- * @param {StateSetter<State>} setter - The setter function or the value to set
55
+ * @param {State} newState - The new state to set
56
+ * @param {object} options - The options for setting the state
57
+ * @param {boolean} [options.forceUpdate] - Whether to force the update even if the state is the same
58
+ * @param {string} [options.identifier] - An optional identifier for the state change
37
59
  * */
38
- protected setState: (newState: State, { forceUpdate, identifier }: {
60
+ protected setSubscribersState: (newState: State, { forceUpdate, identifier }: {
39
61
  forceUpdate?: boolean;
40
62
  identifier?: string;
41
63
  }) => void;
@@ -43,59 +65,68 @@ export declare class GlobalStore<State, Metadata extends BaseMetadata | unknown,
43
65
  * Set the value of the metadata property, this is no reactive and will not trigger a re-render
44
66
  * @param {MetadataSetter<Metadata>} setter - The setter function or the value to set
45
67
  * */
46
- protected setMetadata: MetadataSetter<Metadata>;
47
- protected getMetadata: () => Metadata;
48
- getState: StateGetter<State>;
68
+ setMetadata: MetadataSetter<Metadata>;
69
+ /**
70
+ * Returns the metadata [non-reactive additional information associated with the global state]
71
+ */
72
+ getMetadata: () => Metadata;
73
+ /**
74
+ * Get the current value of the state
75
+ */
76
+ getState: () => State;
77
+ subscribe(subscription: SubscribeCallback<State>, config?: SubscribeCallbackConfig<State>): UnsubscribeCallback;
78
+ subscribe<TDerivate>(selector: SelectorCallback<State, TDerivate>, subscription: SubscribeCallback<TDerivate>, config?: SubscribeCallbackConfig<TDerivate>): UnsubscribeCallback;
49
79
  /**
50
80
  * get the parameters object to pass to the callback functions:
51
81
  * onInit, onStateChanged, onSubscribed, computePreventStateChange
52
82
  * */
53
83
  getConfigCallbackParam: () => StoreTools<State, Metadata>;
54
- protected lastSubscriptionId: string | null;
55
- protected subscribe: (subscription: SubscriberParameters) => () => void;
56
- protected partialUpdateSubscription: (subscriptionId: string, values: Partial<SubscriberParameters>) => void;
84
+ protected subscribeCallback: (subscription: SubscriberParameters) => () => void;
85
+ protected partialUpdateSubscription: (subscription: SubscriberParameters, values: Partial<SubscriberParameters>) => void;
57
86
  protected executeOnSubscribed: (subscription: SubscriberParameters) => void;
58
87
  /**
59
88
  * Returns a custom hook that allows to handle a global state
60
89
  * @returns {[State, StateMutator, Metadata]} - The state, the state setter or the actions map, the metadata
61
90
  * */
62
- getHook: () => StateHook<State, PublicStateMutator, Metadata>;
63
- protected computeSelectedState: ({ subscriptionRef, currentDependencies, }: {
64
- subscriptionRef: SubscriberParameters;
91
+ getMainHook: () => StateHook<State, StateDispatch, PublicStateMutator, Metadata> & {
92
+ removeSubscriptions: () => void;
93
+ dispose: () => void;
94
+ };
95
+ protected computeSelectedState: ({ subscription, currentDependencies, }: {
96
+ subscription: SubscriberParameters;
65
97
  currentDependencies: unknown[] | undefined;
66
98
  }) => unknown;
67
- /**
68
- * @description
69
- * Use this function to create a custom global hook which contains a fragment of the state of another hook
70
- */
71
- createSelectorHook: <RootState, StateMutator, SelectorMetadata extends BaseMetadata, RootSelectorResult, RootDerivate = RootSelectorResult extends never ? RootState : RootSelectorResult>(mainSelector: (state: RootState) => RootSelectorResult, { isEqualRoot: mainIsEqualRoot, isEqual: mainIsEqualFun, name: selectorName, }?: {
72
- isEqual?: (current: RootDerivate, next: RootDerivate) => boolean;
73
- isEqualRoot?: (current: RootState, next: RootState) => boolean;
99
+ createSelectorHook: (selector: (state: unknown) => unknown, options?: {
100
+ isEqual?: ((current: unknown, next: unknown) => boolean) | undefined;
101
+ isEqualRoot?: ((current: unknown, next: unknown) => boolean) | undefined;
102
+ name?: string;
103
+ } | undefined) => StateHook<unknown, unknown, unknown, BaseMetadata>;
104
+ createObservable: (selector: (state: unknown) => unknown, options?: {
105
+ isEqual?: ((current: unknown, next: unknown) => boolean) | undefined;
106
+ isEqualRoot?: ((current: unknown, next: unknown) => boolean) | undefined;
74
107
  name?: string;
75
- }) => StateHook<RootDerivate, StateMutator, SelectorMetadata>;
76
- stateControls: () => [retriever: StateGetter<State>, mutator: PublicStateMutator, metadata: MetadataGetter<Metadata>];
108
+ } | undefined) => ObservableFragment<unknown, unknown, unknown, BaseMetadata>;
77
109
  /**
78
110
  * Returns the state setter or the actions map
79
111
  * @returns {StateMutator} - The state setter or the actions map
80
112
  * */
81
113
  protected getStateOrchestrator: () => PublicStateMutator;
82
114
  /**
115
+ * This is the only setState function that should be exposed outside the class
83
116
  * This is responsible for defining whenever or not the state change should be allowed or prevented
84
117
  * the function also execute the functions:
85
118
  * - onStateChanged (if defined) - this function is executed after the state change
86
119
  * - computePreventStateChange (if defined) - this function is executed before the state change and it should return a boolean value that will be used to determine if the state change should be prevented or not
87
120
  */
88
- protected setStateWrapper: StateSetter<State>;
121
+ setState: (setter: Parameters<React.Dispatch<React.SetStateAction<State>>>[0], { forceUpdate, identifier, }?: {
122
+ forceUpdate?: boolean;
123
+ identifier?: string;
124
+ }) => void;
89
125
  /**
90
126
  * This creates a map of actions that can be used to modify or interact with the state
91
127
  * @returns {ActionCollectionResult<State, Metadata, StateMutator>} - The actions map result of the configuration object passed to the constructor
92
128
  * */
93
- getStoreActionsMap: () => null | ActionCollectionResult<State, Metadata, NonNullable<ActionsConfig>>;
94
- createObservable<Fragment>(mainSelector: (state: State) => Fragment, { isEqualRoot: mainIsEqualRoot, isEqual: mainIsEqualFun, name: selectorName, }?: {
95
- isEqual?: (current: Fragment, next: Fragment) => boolean;
96
- isEqualRoot?: (current: State, next: State) => boolean;
97
- name?: string;
98
- }): ObservableFragment<Fragment>;
129
+ getStoreActionsMap: () => typeof this.actions;
99
130
  removeSubscriptions: () => void;
100
131
  dispose: () => void;
101
132
  }
package/GlobalStore.js CHANGED
@@ -1 +1,128 @@
1
- var t,e;t=this,e=(t,e,r,n,o,i,a,s)=>(()=>{"use strict";var u={45:e=>{e.exports=t},78:t=>{t.exports=e},155:t=>{t.exports=r},361:t=>{t.exports=n},487:t=>{t.exports=o},506:t=>{t.exports=i},673:t=>{t.exports=a},773:t=>{t.exports=s},811:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0});var r=globalThis;r.isDevToolsPresent=Boolean(r.REACT_GLOBAL_STATE_HOOK_DEBUG),e.default=r}},c={};function l(t){var e=c[t];if(void 0!==e)return e.exports;var r=c[t]={exports:{}};return u[t](r,r.exports,l),r.exports}var f={};return(()=>{var t=f;function e(t){return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},e(t)}function r(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var r=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=r){var n,o,i,a,s=[],u=!0,c=!1;try{if(i=(r=r.call(t)).next,0===e){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(s.push(n.value),s.length!==e);u=!0);}catch(t){c=!0,o=t}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return s}}(t,e)||n(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function n(t,e){if(t){if("string"==typeof t)return o(t,e);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?o(t,e):void 0}}function o(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r<e;r++)n[r]=t[r];return n}function i(){i=function(){return r};var t,r={},n=Object.prototype,o=n.hasOwnProperty,a=Object.defineProperty||function(t,e,r){t[e]=r.value},s="function"==typeof Symbol?Symbol:{},u=s.iterator||"@@iterator",c=s.asyncIterator||"@@asyncIterator",l=s.toStringTag||"@@toStringTag";function f(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{f({},"")}catch(t){f=function(t,e,r){return t[e]=r}}function h(t,e,r,n){var o=e&&e.prototype instanceof m?e:m,i=Object.create(o.prototype),s=new A(n||[]);return a(i,"_invoke",{value:L(t,r,s)}),i}function d(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}r.wrap=h;var p="suspendedStart",v="suspendedYield",b="executing",g="completed",y={};function m(){}function S(){}function w(){}var j={};f(j,u,(function(){return this}));var O=Object.getPrototypeOf,x=O&&O(O(M([])));x&&x!==n&&o.call(x,u)&&(j=x);var k=w.prototype=m.prototype=Object.create(j);function C(t){["next","throw","return"].forEach((function(e){f(t,e,(function(t){return this._invoke(e,t)}))}))}function E(t,r){function n(i,a,s,u){var c=d(t[i],t,a);if("throw"!==c.type){var l=c.arg,f=l.value;return f&&"object"==e(f)&&o.call(f,"__await")?r.resolve(f.__await).then((function(t){n("next",t,s,u)}),(function(t){n("throw",t,s,u)})):r.resolve(f).then((function(t){l.value=t,s(l)}),(function(t){return n("throw",t,s,u)}))}u(c.arg)}var i;a(this,"_invoke",{value:function(t,e){function o(){return new r((function(r,o){n(t,e,r,o)}))}return i=i?i.then(o,o):o()}})}function L(e,r,n){var o=p;return function(i,a){if(o===b)throw Error("Generator is already running");if(o===g){if("throw"===i)throw a;return{value:t,done:!0}}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var u=_(s,n);if(u){if(u===y)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===p)throw o=g,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=b;var c=d(e,r,n);if("normal"===c.type){if(o=n.done?g:v,c.arg===y)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=g,n.method="throw",n.arg=c.arg)}}}function _(e,r){var n=r.method,o=e.iterator[n];if(o===t)return r.delegate=null,"throw"===n&&e.iterator.return&&(r.method="return",r.arg=t,_(e,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),y;var i=d(o,e.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,y;var a=i.arg;return a?a.done?(r[e.resultName]=a.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,y):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,y)}function q(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function I(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function A(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(q,this),this.reset(!0)}function M(r){if(r||""===r){var n=r[u];if(n)return n.call(r);if("function"==typeof r.next)return r;if(!isNaN(r.length)){var i=-1,a=function e(){for(;++i<r.length;)if(o.call(r,i))return e.value=r[i],e.done=!1,e;return e.value=t,e.done=!0,e};return a.next=a}}throw new TypeError(e(r)+" is not iterable")}return S.prototype=w,a(k,"constructor",{value:w,configurable:!0}),a(w,"constructor",{value:S,configurable:!0}),S.displayName=f(w,l,"GeneratorFunction"),r.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===S||"GeneratorFunction"===(e.displayName||e.name))},r.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,w):(t.__proto__=w,f(t,l,"GeneratorFunction")),t.prototype=Object.create(k),t},r.awrap=function(t){return{__await:t}},C(E.prototype),f(E.prototype,c,(function(){return this})),r.AsyncIterator=E,r.async=function(t,e,n,o,i){void 0===i&&(i=Promise);var a=new E(h(t,e,n,o),i);return r.isGeneratorFunction(e)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},C(k),f(k,l,"Generator"),f(k,u,(function(){return this})),f(k,"toString",(function(){return"[object Generator]"})),r.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},r.values=M,A.prototype={constructor:A,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(I),!e)for(var r in this)"t"===r.charAt(0)&&o.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var r=this;function n(n,o){return s.type="throw",s.arg=e,r.next=n,o&&(r.method="next",r.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return n("end");if(a.tryLoc<=this.prev){var u=o.call(a,"catchLoc"),c=o.call(a,"finallyLoc");if(u&&c){if(this.prev<a.catchLoc)return n(a.catchLoc,!0);if(this.prev<a.finallyLoc)return n(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return n(a.catchLoc,!0)}else{if(!c)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return n(a.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var n=this.tryEntries[r];if(n.tryLoc<=this.prev&&o.call(n,"finallyLoc")&&this.prev<n.finallyLoc){var i=n;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,y):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),y},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),I(r),y}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;I(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:M(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),y}},r}function a(t){var r=function(t){if("object"!=e(t)||!t)return t;var r=t[Symbol.toPrimitive];if(void 0!==r){var n=r.call(t,"string");if("object"!=e(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==e(r)?r:r+""}Object.defineProperty(t,"__esModule",{value:!0}),t.GlobalStore=void 0;var s,u=l(155),c=l(506),h=l(773),d=l(487),p=l(673),v=l(361),b=l(78),g=l(45),y=(s=l(811))&&s.__esModule?s:{default:s},m=function(){return t=function t(e){var o,s,l=this,f=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{metadata:{}};!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.wasDisposed=!1,this.actionsConfig=null,this.callbacks=null,this.actions=null,this.subscribers=new Map,this.initialize=function(){return t=l,e=void 0,r=i().mark((function t(){var e,r,n,o,a,s;return i().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(Object.keys(null!==(e=this.actionsConfig)&&void 0!==e?e:{}).length>0&&(this.actions=this.getStoreActionsMap()),n=this.onInit,o=null!==(r=this.callbacks)&&void 0!==r?r:{},a=o.onInit,n||a){t.next=6;break}return t.abrupt("return");case 6:s=this.getConfigCallbackParam(),null==n||n(s),(0,h.isNil)(a)||null==a||a(s);case 9:case"end":return t.stop()}}),t,this)})),new(e||(e=Promise))((function(n,o){function i(t){try{s(r.next(t))}catch(t){o(t)}}function a(t){try{s(r.throw(t))}catch(t){o(t)}}function s(t){var r;t.done?n(t.value):(r=t.value,r instanceof e?r:new e((function(t){t(r)}))).then(i,a)}s((r=r.apply(t,[])).next())}));var t,e,r},this.executeSetStateForSubscriber=function(t,e){var r,n,o,i=t.selector,a=t.callback,s=t.currentState,u=t.getConfig,c=null!==(r=null==u?void 0:u())&&void 0!==r?r:{};if(!e.forceUpdate&&(null!==(n=null==c?void 0:c.isEqualRoot)&&void 0!==n?n:function(t,e){return t===e})(e.currentState,e.newState))return{didUpdate:!1};var f=i?i(e.newState):e.newState;return!e.forceUpdate&&(null!==(o=null==c?void 0:c.isEqual)&&void 0!==o?o:function(t,e){return t===e})(s,f)?{didUpdate:!1}:(l.partialUpdateSubscription(t.subscriptionId,{currentState:f}),a({state:f},{identifier:e.identifier}),{didUpdate:!0})},this.setState=function(t,e){var r=e.forceUpdate,o=e.identifier,i=l.state;if(r||i!==t){l.state=t;var a,s={forceUpdate:r,newState:t,currentState:i,identifier:o},u=function(t){var e="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!e){if(Array.isArray(t)||(e=n(t))){e&&(t=e);var r=0,o=function(){};return{s:o,n:function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,s=!1;return{s:function(){e=e.call(t)},n:function(){var t=e.next();return a=t.done,t},e:function(t){s=!0,i=t},f:function(){try{a||null==e.return||e.return()}finally{if(s)throw i}}}}(l.subscribers.values());try{for(u.s();!(a=u.n()).done;){var c=a.value;l.executeSetStateForSubscriber(c,s)}}catch(t){u.e(t)}finally{u.f()}}},this.setMetadata=function(t){var e=(0,c.isFunction)(t)?t(l.metadata):t;l.metadata=e},this.getMetadata=function(){return l.metadata},this.getState=function(t,e,r){var n;if(!t)return l.state;var o=(0,c.isFunction)(e),i=o?t:void 0,a=o?e:t,s=null!==(n=o?r:e)&&void 0!==n?n:void 0,u=i?i(l.state):l.state;(null==s?void 0:s.skipFirst)||a(u);var f=(0,b.uniqueId)("gs:");return l.subscribe({subscriptionId:f,selector:i,getConfig:function(){return s},currentState:u,callback:function(t){var e=t.state;return a(e)}}),function(){l.subscribers.delete(f)}},this.getConfigCallbackParam=function(){var t=l.setMetadata,e=l.getMetadata,r=l.getState,n=l.actions;return{setMetadata:t,getMetadata:e,getState:r,setState:l.setStateWrapper,actions:n}},this.lastSubscriptionId=null,this.subscribe=function(t){var e=t.subscriptionId;return l.executeOnSubscribed(t),l.subscribers.set(e,t),l.lastSubscriptionId=e,function(){l.subscribers.delete(e)}},this.partialUpdateSubscription=function(t,e){var r=l.subscribers.get(t);(0,d.isRecord)(r)&&Object.assign(r,e)},this.executeOnSubscribed=function(t){var e,r=l.onSubscribed,n=null===(e=l.callbacks)||void 0===e?void 0:e.onSubscribed;if(r||n){var o=l.getConfigCallbackParam();null==r||r(o,t),null==n||n(o,t)}},this.getHook=function(){var t=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];if(l.wasDisposed)throw new Error("The global state was disposed");var r=(0,p.isArray)(e)?{dependencies:e}:null!=e?e:{},n=(0,u.useRef)({selector:t,config:r}),o=n.current.config.dependencies;n.current.selector=t,n.current.config=r;var i=(0,u.useMemo)((function(){var t=function(t){var e=n.current.selector;return(0,c.isFunction)(e)?e(t):t},e={subscriptionId:(0,b.uniqueId)("ss:"),currentState:t(l.state),selector:t,getConfig:function(){return n.current.config},callback:function(){throw new Error("Callback not set")}};return{subscribe:function(t){return e.callback=t,l.subscribe(e)},getSnapshot:function(){return e.currentState},subscription:e}}),[]),a=i.subscribe,s=i.getSnapshot,f=i.subscription;return(0,u.useSyncExternalStore)(a,s,s),[l.computeSelectedState({subscriptionRef:f,currentDependencies:o}),l.getStateOrchestrator(),l.metadata]};return t.stateControls=l.stateControls,t.createSelectorHook=l.createSelectorHook,t.createObservable=l.createObservable,t.removeSubscriptions=l.removeSubscriptions,t.dispose=l.dispose,t},this.computeSelectedState=function(t){var e,r=t.subscriptionRef,n=t.currentDependencies;if(!r.selector)return r.currentState;var o=(null!==(e=r.getConfig())&&void 0!==e?e:{}).dependencies;return n===o||(null==n?void 0:n.length)===(null==o?void 0:o.length)&&(0,p.shallowCompare)(n,o)||l.partialUpdateSubscription(r.subscriptionId,{currentState:r.selector(l.state)}),r.currentState},this.createSelectorHook=function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=n.isEqualRoot,i=n.isEqual,a=n.name,s=r(l.stateControls(),3),u=s[0],f=s[1],h=s[2],d=u(),p=(null!=e?e:function(t){return t})(d),v=new t(p,{name:null!=a?a:(0,b.uniqueId)("sh:")}),g=r(v.stateControls(),2),y=g[0],m=g[1],S=u((function(t){if(!(null!=o?o:Object.is)(d,t)){d=t;var r=e(t);(null!=i?i:Object.is)(p,r)||(p=r,m(r))}}),{skipFirst:!0}),w=v.getHook(),j=function(t,e){return[r((0,c.isFunction)(t)?w(t,e):w(),1)[0],f,h()]};return j.stateControls=function(){return[y,f,h]},j.createSelectorHook=v.createSelectorHook,j.createObservable=l.createObservable.bind(j),j.removeSubscriptions=function(){S(),v.removeSubscriptions()},j.dispose=function(){j.removeSubscriptions(),v.dispose()},j},this.stateControls=function(){var t=l.getStateOrchestrator(),e=l.getMetadata;return[l.getState,t,e]},this.getStateOrchestrator=function(){return l.actions?l.actions:l.setStateWrapper},this.setStateWrapper=function(t){var e,r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=n.forceUpdate,i=n.identifier,a=l.state,s=(0,c.isFunction)(t)?t(a):t;if(o||l.state!==s){var u=l.setMetadata,f=l.getMetadata,h=l.getState,d=l.actions,p={setMetadata:u,getMetadata:f,setState:l.setState,getState:h,actions:d,previousState:a,state:s,identifier:i},v=l.computePreventStateChange,b=null===(e=l.callbacks)||void 0===e?void 0:e.computePreventStateChange;if((v||b)&&((null==v?void 0:v(p))||(null==b?void 0:b(p))))return;l.setState(s,{forceUpdate:o,identifier:i});var g=l.onStateChanged,y=null===(r=l.callbacks)||void 0===r?void 0:r.onStateChanged;(g||y)&&(null==g||g(p),null==y||y(p))}},this.getStoreActionsMap=function(){if(!(0,d.isRecord)(l.actionsConfig))return null;var t=l.actionsConfig,e=l.setMetadata,r=l.setStateWrapper,n=l.getState,o=l.getMetadata,i=Object.keys(t).reduce((function(s,u){var c,l,f;return Object.assign(s,(c={},f=function(){for(var a=t[u],s=arguments.length,c=new Array(s),l=0;l<s;l++)c[l]=arguments[l];var f=a.apply(i,c);return"function"!=typeof f&&(0,v.throwWrongKeyOnActionCollectionConfig)(u),f.call(i,{setState:r,getState:n,setMetadata:e,getMetadata:o,actions:i})},(l=a(l=u))in c?Object.defineProperty(c,l,{value:f,enumerable:!0,configurable:!0,writable:!0}):c[l]=f,c)),s}),{});return i},this.removeSubscriptions=function(){l.subscribers.clear()},this.dispose=function(){l.wasDisposed=!0,l.removeSubscriptions(),l._name="",l.actionsConfig=null,l.callbacks=null,l.metadata={},l.actions=null,l.state=Object.create(null)};var m=f.metadata,S=f.callbacks,w=f.actions,j=f.name;if(this.state=e,this._name=null!=j?j:(0,b.uniqueId)("gs:"),this.metadata=null!=m?m:{},this.callbacks=null!=S?S:null,this.actionsConfig=null!=w?w:null,y.default.isDevToolsPresent){var O=(0,g.generateStackHash)(null!==(o=(new Error).stack)&&void 0!==o?o:"");null===(s=y.default.REACT_GLOBAL_STATE_HOOK_DEBUG)||void 0===s||s.call(y.default,this,f,O)}this.constructor!==t||this.initialize()},e=[{key:"createObservable",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.isEqualRoot,o=e.isEqual,i=e.name,a=r(this.stateControls(),1)[0],s=[],u=a(),l=(null!=t?t:function(t){return t})(a()),f=a((function(e){if(!(null!=n?n:Object.is)(u,e)){u=e;var r=t(e);(null!=o?o:Object.is)(l,r)||(l=r,s.forEach((function(t){return t()})))}}),{skipFirst:!0}),h=function(t,e,r){var n;if(!t)return l;var o=(0,c.isFunction)(e),i=o?t:void 0,a=o?e:t,u=null!==(n=o?r:e)&&void 0!==n?n:void 0,f=function(){return a(i?i(l):l)};(null==u?void 0:u.skipFirst)||f();var h=function(){f()};return s.push(h),function(){s.splice(s.indexOf(h),1)}};return h._name=null!=i?i:(0,b.uniqueId)("ob:"),h.createObservable=this.createObservable.bind(h),h.removeSubscriptions=function(){s.forEach((function(t){return t()})),s.length=0,f()},h.stateControls=function(){return[h]},h}}],e&&function(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,a(n.key),n)}}(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e}();t.GlobalStore=m,t.default=m})(),f})(),"object"==typeof exports&&"object"==typeof module?module.exports=e(require("./generateStackHash.js"),require("./uniqueId.js"),require("react"),require("./throwWrongKeyOnActionCollectionConfig.js"),require("./isRecord.js"),require("json-storage-formatter/isFunction"),require("./shallowCompare.js"),require("json-storage-formatter/isNil")):"function"==typeof define&&define.amd?define(["./generateStackHash.js","./uniqueId.js","react","./throwWrongKeyOnActionCollectionConfig.js","./isRecord.js","json-storage-formatter/isFunction","./shallowCompare.js","json-storage-formatter/isNil"],e):"object"==typeof exports?exports["react-hooks-global-states"]=e(require("./generateStackHash.js"),require("./uniqueId.js"),require("react"),require("./throwWrongKeyOnActionCollectionConfig.js"),require("./isRecord.js"),require("json-storage-formatter/isFunction"),require("./shallowCompare.js"),require("json-storage-formatter/isNil")):t["react-hooks-global-states"]=e(t["./generateStackHash.js"],t["./uniqueId.js"],t.react,t["./throwWrongKeyOnActionCollectionConfig.js"],t["./isRecord.js"],t["json-storage-formatter/isFunction"],t["./shallowCompare.js"],t["json-storage-formatter/isNil"]);
1
+ var t,e;t=this,e=(t,e,r,n,i,o,a)=>/******/(()=>{
2
+ /******/"use strict";
3
+ /******/var s={
4
+ /***/78:
5
+ /***/e=>{e.exports=t;
6
+ /***/},
7
+ /***/155:
8
+ /***/t=>{t.exports=e;
9
+ /***/},
10
+ /***/361:
11
+ /***/t=>{t.exports=r;
12
+ /***/},
13
+ /***/487:
14
+ /***/t=>{t.exports=n;
15
+ /***/},
16
+ /***/506:
17
+ /***/t=>{t.exports=i;
18
+ /***/},
19
+ /***/673:
20
+ /***/t=>{t.exports=o;
21
+ /***/},
22
+ /***/773:
23
+ /***/t=>{t.exports=a;
24
+ /***/},
25
+ /***/811:
26
+ /***/(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0});var r=globalThis;r.isDevToolsPresent=Boolean(r.REACT_GLOBAL_STATE_HOOK_DEBUG),e.default=r}
27
+ /***/
28
+ /******/},c={};
29
+ /************************************************************************/
30
+ /******/
31
+ /******/
32
+ /******/
33
+ /******/
34
+ /******/function u(t){
35
+ /******/
36
+ /******/var e=c[t];
37
+ /******/if(void 0!==e)
38
+ /******/return e.exports;
39
+ /******/
40
+ /******/
41
+ /******/var r=c[t]={
42
+ /******/
43
+ /******/
44
+ /******/exports:{}
45
+ /******/};
46
+ /******/
47
+ /******/
48
+ /******/
49
+ /******/
50
+ /******/
51
+ /******/return s[t](r,r.exports,u),r.exports;
52
+ /******/}
53
+ /******/
54
+ /************************************************************************/var l={};
55
+ /******/return(()=>{var t=l;function e(t){return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},e(t)}function r(t,e){if(t){if("string"==typeof t)return n(t,e);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(t,e):void 0}}function n(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r<e;r++)n[r]=t[r];return n}function i(){i=function(){return r};var t,r={},n=Object.prototype,o=n.hasOwnProperty,a=Object.defineProperty||function(t,e,r){t[e]=r.value},s="function"==typeof Symbol?Symbol:{},c=s.iterator||"@@iterator",u=s.asyncIterator||"@@asyncIterator",l=s.toStringTag||"@@toStringTag";function f(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{f({},"")}catch(t){f=function(t,e,r){return t[e]=r}}function h(t,e,r,n){var i=e&&e.prototype instanceof m?e:m,o=Object.create(i.prototype),s=new A(n||[]);return a(o,"_invoke",{value:M(t,r,s)}),o}function d(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}r.wrap=h;var b="suspendedStart",v="suspendedYield",p="executing",g="completed",y={};function m(){}function S(){}function w(){}var j={};f(j,c,(function(){return this}));var O=Object.getPrototypeOf,k=O&&O(O(P([])));k&&k!==n&&o.call(k,c)&&(j=k);var x=w.prototype=m.prototype=Object.create(j);function C(t){["next","throw","return"].forEach((function(e){f(t,e,(function(t){return this._invoke(e,t)}))}))}function E(t,r){function n(i,a,s,c){var u=d(t[i],t,a);if("throw"!==u.type){var l=u.arg,f=l.value;return f&&"object"==e(f)&&o.call(f,"__await")?r.resolve(f.__await).then((function(t){n("next",t,s,c)}),(function(t){n("throw",t,s,c)})):r.resolve(f).then((function(t){l.value=t,s(l)}),(function(t){return n("throw",t,s,c)}))}c(u.arg)}var i;a(this,"_invoke",{value:function(t,e){function o(){return new r((function(r,i){n(t,e,r,i)}))}return i=i?i.then(o,o):o()}})}function M(e,r,n){var i=b;return function(o,a){if(i===p)throw Error("Generator is already running");if(i===g){if("throw"===o)throw a;return{value:t,done:!0}}for(n.method=o,n.arg=a;;){var s=n.delegate;if(s){var c=L(s,n);if(c){if(c===y)continue;return c}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(i===b)throw i=g,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);i=p;var u=d(e,r,n);if("normal"===u.type){if(i=n.done?g:v,u.arg===y)continue;return{value:u.arg,done:n.done}}"throw"===u.type&&(i=g,n.method="throw",n.arg=u.arg)}}}function L(e,r){var n=r.method,i=e.iterator[n];if(i===t)return r.delegate=null,"throw"===n&&e.iterator.return&&(r.method="return",r.arg=t,L(e,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),y;var o=d(i,e.iterator,r.arg);if("throw"===o.type)return r.method="throw",r.arg=o.arg,r.delegate=null,y;var a=o.arg;return a?a.done?(r[e.resultName]=a.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,y):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,y)}function _(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function q(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function A(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(_,this),this.reset(!0)}function P(r){if(r||""===r){var n=r[c];if(n)return n.call(r);if("function"==typeof r.next)return r;if(!isNaN(r.length)){var i=-1,a=function e(){for(;++i<r.length;)if(o.call(r,i))return e.value=r[i],e.done=!1,e;return e.value=t,e.done=!0,e};return a.next=a}}throw new TypeError(e(r)+" is not iterable")}return S.prototype=w,a(x,"constructor",{value:w,configurable:!0}),a(w,"constructor",{value:S,configurable:!0}),S.displayName=f(w,l,"GeneratorFunction"),r.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===S||"GeneratorFunction"===(e.displayName||e.name))},r.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,w):(t.__proto__=w,f(t,l,"GeneratorFunction")),t.prototype=Object.create(x),t},r.awrap=function(t){return{__await:t}},C(E.prototype),f(E.prototype,u,(function(){return this})),r.AsyncIterator=E,r.async=function(t,e,n,i,o){void 0===o&&(o=Promise);var a=new E(h(t,e,n,i),o);return r.isGeneratorFunction(e)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},C(x),f(x,l,"Generator"),f(x,c,(function(){return this})),f(x,"toString",(function(){return"[object Generator]"})),r.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},r.values=P,A.prototype={constructor:A,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(q),!e)for(var r in this)"t"===r.charAt(0)&&o.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var r=this;function n(n,i){return s.type="throw",s.arg=e,r.next=n,i&&(r.method="next",r.arg=t),!!i}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return n("end");if(a.tryLoc<=this.prev){var c=o.call(a,"catchLoc"),u=o.call(a,"finallyLoc");if(c&&u){if(this.prev<a.catchLoc)return n(a.catchLoc,!0);if(this.prev<a.finallyLoc)return n(a.finallyLoc)}else if(c){if(this.prev<a.catchLoc)return n(a.catchLoc,!0)}else{if(!u)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return n(a.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var n=this.tryEntries[r];if(n.tryLoc<=this.prev&&o.call(n,"finallyLoc")&&this.prev<n.finallyLoc){var i=n;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,y):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),y},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),q(r),y}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var i=n.arg;q(r)}return i}}throw Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:P(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),y}},r}function o(t){var r=function(t){if("object"!=e(t)||!t)return t;var r=t[Symbol.toPrimitive];if(void 0!==r){var n=r.call(t,"string");if("object"!=e(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==e(r)?r:r+""}Object.defineProperty(t,"__esModule",{value:!0}),t.GlobalStore=void 0;var a,s=u(155),c=u(506),f=u(773),h=u(487),d=u(673),b=u(361),v=u(78),p=(a=u(811))&&a.__esModule?a:{default:a},g=function(){return t=function t(e){var n,a,u=this,l=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{metadata:{}};!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.actionsConfig=null,this.callbacks=null,
56
+ /**
57
+ * @description If the actionsConfig is defined, this will be a map of actions that can be used to modify or interact with the state
58
+ * */
59
+ this.actions=null,this.subscribers=new Set,
60
+ /**
61
+ * @description
62
+ * Initializes the global store, setting up the main hook and actions map if applicable,
63
+ */
64
+ this.initialize=function(){return t=u,e=void 0,r=i().mark((function t(){var e,r,n,o,a;return i().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(Object.keys(null!==(e=this.actionsConfig)&&void 0!==e?e:{}).length>0&&(this.actions=this.getStoreActionsMap()),this.use=this.getMainHook(),this.configurationCallbackParam=this.getConfigCallbackParam(),n=this.onInit,o=null!==(r=this.callbacks)&&void 0!==r?r:{},a=o.onInit,n||a){t.next=8;break}return t.abrupt("return");case 8:null==n||n(this.configurationCallbackParam),(0,f.isNil)(a)||null==a||a(this.configurationCallbackParam);case 10:case"end":return t.stop()}}),t,this)})),new(e||(e=Promise))((function(n,i){function o(t){try{s(r.next(t))}catch(t){i(t)}}function a(t){try{s(r.throw(t))}catch(t){i(t)}}function s(t){var r;t.done?n(t.value):(r=t.value,r instanceof e?r:new e((function(t){t(r)}))).then(o,a)}s((r=r.apply(t,[])).next())}));var t,e,r},
65
+ /**
66
+ * set the state for a single subscriber
67
+ * validate if the state should be updated by comparing the previous state and the new state
68
+ */
69
+ this.executeSetStateForSubscriber=function(t,e){var r,n,i,o=t.selector,a=t.callback,s=t.currentState,c=t.getConfig,l=null!==(r=null==c?void 0:c())&&void 0!==r?r:{};if(!e.forceUpdate&&(null!==(n=null==l?void 0:l.isEqualRoot)&&void 0!==n?n:function(t,e){return t===e})(e.currentState,e.newState))return{didUpdate:!1};var f=o?o(e.newState):e.newState;return!e.forceUpdate&&(null!==(i=null==l?void 0:l.isEqual)&&void 0!==i?i:function(t,e){return t===e})(s,f)?{didUpdate:!1}:(u.partialUpdateSubscription(t,{currentState:f}),a({state:f},{identifier:e.identifier}),{didUpdate:!0})},
70
+ /**
71
+ * set the state and update all the subscribers
72
+ * @param {State} newState - The new state to set
73
+ * @param {object} options - The options for setting the state
74
+ * @param {boolean} [options.forceUpdate] - Whether to force the update even if the state is the same
75
+ * @param {string} [options.identifier] - An optional identifier for the state change
76
+ * */
77
+ this.setSubscribersState=function(t,e){var n=e.forceUpdate,i=e.identifier,o=u.state;if(n||o!==t){u.state=t;var a,s={forceUpdate:n,newState:t,currentState:o,identifier:i},c=function(t){var e="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!e){if(Array.isArray(t)||(e=r(t))){e&&(t=e);var n=0,i=function(){};return{s:i,n:function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){e=e.call(t)},n:function(){var t=e.next();return a=t.done,t},e:function(t){s=!0,o=t},f:function(){try{a||null==e.return||e.return()}finally{if(s)throw o}}}}(u.subscribers.values());try{for(c.s();!(a=c.n()).done;){var l=a.value;u.executeSetStateForSubscriber(l,s)}}catch(t){c.e(t)}finally{c.f()}}},
78
+ /**
79
+ * Set the value of the metadata property, this is no reactive and will not trigger a re-render
80
+ * @param {MetadataSetter<Metadata>} setter - The setter function or the value to set
81
+ * */
82
+ this.setMetadata=function(t){var e=(0,c.isFunction)(t)?t(u.metadata):t;u.metadata=e},
83
+ /**
84
+ * Returns the metadata [non-reactive additional information associated with the global state]
85
+ */
86
+ this.getMetadata=function(){return u.metadata},
87
+ /**
88
+ * Get the current value of the state
89
+ */
90
+ this.getState=function(){return u.state},
91
+ /**
92
+ * get the parameters object to pass to the callback functions:
93
+ * onInit, onStateChanged, onSubscribed, computePreventStateChange
94
+ * */
95
+ this.getConfigCallbackParam=function(){var t=u.setMetadata,e=u.getMetadata,r=u.getState,n=u.subscribe,i=u.actions;return{setMetadata:t,getMetadata:e,getState:r,subscribe:n,setState:u.setState,actions:i}},this.subscribeCallback=function(t){return u.executeOnSubscribed(t),u.subscribers.add(t),function(){u.subscribers.delete(t)}},this.partialUpdateSubscription=function(t,e){(0,h.isRecord)(t)&&Object.assign(t,e)},this.executeOnSubscribed=function(t){var e,r=u.onSubscribed,n=null===(e=u.callbacks)||void 0===e?void 0:e.onSubscribed;(r||n)&&(null==r||r(u.configurationCallbackParam,t),null==n||n(u.configurationCallbackParam,t))},
96
+ /**
97
+ * Returns a custom hook that allows to handle a global state
98
+ * @returns {[State, StateMutator, Metadata]} - The state, the state setter or the actions map, the metadata
99
+ * */
100
+ this.getMainHook=function(){var t=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=(0,d.isArray)(e)?{dependencies:e}:null!=e?e:{},n=(0,s.useRef)({selector:t,config:r}),i=n.current.config.dependencies;n.current.selector=t,n.current.config=r;var o=(0,s.useMemo)((function(){var t=function(t){var e=n.current.selector;return(0,c.isFunction)(e)?e(t):t},e={currentState:t(u.state),selector:t,getConfig:function(){return n.current.config},callback:function(){throw new Error("Callback not set")}},r=function(){return e.currentState};return{subscribe:function(t){return e.callback=t,u.subscribeCallback(e)},getSnapshot:r,getServerSnapshot:r,subscription:e}}),[]),a=o.subscribe,l=o.getSnapshot,f=o.getServerSnapshot,h=o.subscription;return(0,s.useSyncExternalStore)(a,l,f),[u.computeSelectedState({subscription:h,currentDependencies:i}),u.getStateOrchestrator(),u.metadata]},e={setMetadata:u.setMetadata.bind(u),getMetadata:u.getMetadata.bind(u),actions:u.actions,setState:u.actions?null:u.setState,getState:u.getState.bind(u),subscribe:u.subscribe.bind(u),createSelectorHook:u.createSelectorHook.bind(t),createObservable:u.createObservable.bind(t),removeSubscriptions:u.removeSubscriptions.bind(u),dispose:u.dispose.bind(u)};
101
+ /**
102
+ * Extended properties and methods of the hook
103
+ */return Object.assign(t,e),t},this.computeSelectedState=function(t){var e,r=t.subscription,n=t.currentDependencies;if(!r.selector)return r.currentState;var i=(null!==(e=r.getConfig())&&void 0!==e?e:{}).dependencies;return n===i||(null==n?void 0:n.length)===(null==i?void 0:i.length)&&(0,d.shallowCompare)(n,i)||u.partialUpdateSubscription(r,{currentState:r.selector(u.state)}),r.currentState},this.createSelectorHook=m.bind(this),this.createObservable=y.bind(this),
104
+ /**
105
+ * Returns the state setter or the actions map
106
+ * @returns {StateMutator} - The state setter or the actions map
107
+ * */
108
+ this.getStateOrchestrator=function(){return u.actions?u.actions:u.setState},
109
+ /**
110
+ * This is the only setState function that should be exposed outside the class
111
+ * This is responsible for defining whenever or not the state change should be allowed or prevented
112
+ * the function also execute the functions:
113
+ * - onStateChanged (if defined) - this function is executed after the state change
114
+ * - computePreventStateChange (if defined) - this function is executed before the state change and it should return a boolean value that will be used to determine if the state change should be prevented or not
115
+ */
116
+ this.setState=function(t){var e,r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=n.forceUpdate,o=n.identifier,a=u.state,s=(0,c.isFunction)(t)?t(a):t;if(i||u.state!==s){var l=u.setMetadata,f=u.getMetadata,h=u.getState,d=u.actions,b={setMetadata:l,getMetadata:f,setState:u.setSubscribersState,getState:h,actions:d,previousState:a,state:s,identifier:o},v=u.computePreventStateChange,p=null===(e=u.callbacks)||void 0===e?void 0:e.computePreventStateChange;if((v||p)&&((null==v?void 0:v(b))||(null==p?void 0:p(b))))return;u.setSubscribersState(s,{forceUpdate:i,identifier:o});var g=u.onStateChanged,y=null===(r=u.callbacks)||void 0===r?void 0:r.onStateChanged;(g||y)&&(null==g||g(b),null==y||y(b))}},
117
+ /**
118
+ * This creates a map of actions that can be used to modify or interact with the state
119
+ * @returns {ActionCollectionResult<State, Metadata, StateMutator>} - The actions map result of the configuration object passed to the constructor
120
+ * */
121
+ this.getStoreActionsMap=function(){if(!(0,h.isRecord)(u.actionsConfig))return null;var t=u.actionsConfig,e=u.setMetadata,r=u.setState,n=u.getState,i=u.getMetadata,a=Object.keys(t).reduce((function(s,c){var u,l,f;return Object.assign(s,(u={},f=function(){for(var o=t[c],s=arguments.length,u=new Array(s),l=0;l<s;l++)u[l]=arguments[l];var f=o.apply(a,u);return"function"!=typeof f&&(0,b.throwWrongKeyOnActionCollectionConfig)(c),f.call(a,{setState:r,getState:n,setMetadata:e,getMetadata:i,actions:a})},(l=o(l=c))in u?Object.defineProperty(u,l,{value:f,enumerable:!0,configurable:!0,writable:!0}):u[l]=f,u)),s}),{});return a},this.removeSubscriptions=function(){u.subscribers.clear()},this.dispose=function(){u.removeSubscriptions(),u._name="",u.actionsConfig=null,u.callbacks=null,u.metadata={},u.actions=null,u.state=Object.create(null)};var g=l.metadata,S=l.callbacks,w=l.actions,j=l.name;if(this.state=e,this._name=null!=j?j:(0,v.uniqueId)("gs:"),this.metadata=null!=g?g:{},this.callbacks=null!=S?S:null,this.actionsConfig=null!=w?w:null,p.default.isDevToolsPresent){var O=null!==(n=(new Error).stack)&&void 0!==n?n:"";null===(a=p.default.REACT_GLOBAL_STATE_HOOK_DEBUG)||void 0===a||a.call(p.default,this,l,O)}this.constructor!==t||this.initialize()},e=[{key:"subscribe",value:function(){for(var t=this,e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];var i,o=r[0],a=r[1],s=r[2],u=(0,c.isFunction)(a),l=u?o:void 0,f=u?a:o,h=null!==(i=u?s:a)&&void 0!==i?i:void 0,d=l?l(this.state):this.state;(null==h?void 0:h.skipFirst)||f(d);var b={selector:l,getConfig:function(){return h},currentState:d,callback:function(t){var e=t.state;return f(e)}};return this.subscribeCallback(b),function(){t.subscribers.delete(b)}}}],e&&function(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,o(n.key),n)}}(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e}();function y(t,e){var r=null==e?void 0:e.name,n=null==e?void 0:e.isEqualRoot,i=null==e?void 0:e.isEqual,o=this.getState(),a=(null!=t?t:function(t){return t})(o),s=new g(a,{name:null!=r?r:(0,v.uniqueId)("sh:")}),c=this.subscribe((function(e){if(!(null!=n?n:Object.is)(o,e)){o=e;var r=t(e);(null!=i?i:Object.is)(a,r)||(a=r,s.setState(r))}}),{skipFirst:!0}),u=this.actions?null:this.setState,l=s.subscribe.bind(s),f={setMetadata:this.setMetadata.bind(this),getMetadata:this.getMetadata.bind(this),actions:this.actions,setState:u,getState:s.getState.bind(s),subscribe:s.subscribe.bind(s),createSelectorHook:m.bind(l),createObservable:y.bind(l),removeSubscriptions:function(){c(),s.removeSubscriptions()},dispose:function(){s.removeSubscriptions(),s.dispose()}};return Object.assign(l,f),l}
122
+ /**
123
+ * @description
124
+ * Creates a derived hook bound to a selected fragment of the root state.
125
+ * The derived hook re-renders only when the selected value changes and
126
+ * exposes the same API as the parent state hook.
127
+ */function m(t,e){var n,i=this,o=null==e?void 0:e.name,a=null==e?void 0:e.isEqualRoot,s=null==e?void 0:e.isEqual,c=this.getState(),u=(null!=t?t:function(t){return t})(c),l=new g(u,{name:null!=o?o:(0,v.uniqueId)("sh:")}),f=this.subscribe((function(e){if(!(null!=a?a:Object.is)(c,e)){c=e;var r=t(e);(null!=s?s:Object.is)(u,r)||(u=r,l.setState(r))}}),{skipFirst:!0}),h=null!==(n=this.actions)&&void 0!==n?n:this.setState,d=this.actions?null:this.setState,b=function(){return[(t=l.use.apply(l,arguments),function(t){if(Array.isArray(t))return t}(t)||function(t){var e=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=e){var r,n,i,o,a=[],s=!0,c=!1;try{for(i=(e=e.call(t)).next;!(s=(r=i.call(e)).done)&&(a.push(r.value),1!==a.length);s=!0);}catch(t){c=!0,n=t}finally{try{if(!s&&null!=e.return&&(o=e.return(),Object(o)!==o))return}finally{if(c)throw n}}return a}}(t)||r(t,1)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}())[0],h,i.getMetadata()];var t},p={setMetadata:this.setMetadata.bind(this),getMetadata:this.getMetadata.bind(this),actions:this.actions,setState:d,getState:this.getState.bind(this),subscribe:this.subscribe.bind(this),createSelectorHook:m.bind(b),createObservable:y.bind(b),removeSubscriptions:function(){f(),l.removeSubscriptions()},dispose:function(){l.removeSubscriptions(),l.dispose()}};return Object.assign(b,p),b}t.GlobalStore=g,t.default=g})(),l;
128
+ /******/})(),"object"==typeof exports&&"object"==typeof module?module.exports=e(require("./uniqueId.js"),require("react"),require("./throwWrongKeyOnActionCollectionConfig.js"),require("./isRecord.js"),require("json-storage-formatter/isFunction"),require("./shallowCompare.js"),require("json-storage-formatter/isNil")):"function"==typeof define&&define.amd?define(["./uniqueId.js","react","./throwWrongKeyOnActionCollectionConfig.js","./isRecord.js","json-storage-formatter/isFunction","./shallowCompare.js","json-storage-formatter/isNil"],e):"object"==typeof exports?exports["react-hooks-global-states"]=e(require("./uniqueId.js"),require("react"),require("./throwWrongKeyOnActionCollectionConfig.js"),require("./isRecord.js"),require("json-storage-formatter/isFunction"),require("./shallowCompare.js"),require("json-storage-formatter/isNil")):t["react-hooks-global-states"]=e(t["./uniqueId.js"],t.react,t["./throwWrongKeyOnActionCollectionConfig.js"],t["./isRecord.js"],t["json-storage-formatter/isFunction"],t["./shallowCompare.js"],t["json-storage-formatter/isNil"]);
@@ -6,7 +6,7 @@ import { GlobalStore } from './GlobalStore';
6
6
  * by implementing the abstract methods onInitialize and onChange.
7
7
  * You can use this class to create a store with async storage.
8
8
  */
9
- export declare abstract class GlobalStoreAbstract<State, Metadata extends BaseMetadata | unknown, ActionsConfig extends ActionCollectionConfig<State, Metadata> | unknown> extends GlobalStore<State, Metadata, ActionsConfig> {
9
+ export declare abstract class GlobalStoreAbstract<State, Metadata extends BaseMetadata, ActionsConfig extends ActionCollectionConfig<State, Metadata> | unknown> extends GlobalStore<State, Metadata, ActionsConfig> {
10
10
  protected onInit: (args: StoreTools<State, Metadata>) => void;
11
11
  protected onStateChanged: (args: StoreTools<State, Metadata> & StateChanges<State>) => void;
12
12
  protected abstract onInitialize: (args: StoreTools<State, Metadata>) => void;
@@ -1 +1,41 @@
1
- var t;t=t=>(()=>{"use strict";var e={778:e=>{e.exports=t}},o={};function r(t){var n=o[t];if(void 0!==n)return n.exports;var i=o[t]={exports:{}};return e[t](i,i.exports,r),i.exports}var n={};return(()=>{var t=n;function e(t){return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},e(t)}function o(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(t){}return(o=function(){return!!t})()}function i(t){return i=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},i(t)}function c(t,e){return c=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},c(t,e)}Object.defineProperty(t,"__esModule",{value:!0}),t.GlobalStoreAbstract=void 0;var u=function(t){function r(){var t;return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,r),(t=function(t,r,n){return r=i(r),function(t,o){if(o&&("object"==e(o)||"function"==typeof o))return o;if(void 0!==o)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(t,o()?Reflect.construct(r,n||[],i(t).constructor):r.apply(t,n))}(this,r,arguments)).onInit=function(e){t.onInitialize(e)},t.onStateChanged=function(e){t.onChange(e)},t}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&c(t,e)}(r,t),n=r,Object.defineProperty(n,"prototype",{writable:!1}),n;var n}(r(778).GlobalStore);t.GlobalStoreAbstract=u,t.default=u})(),n})(),"object"==typeof exports&&"object"==typeof module?module.exports=t(require("./GlobalStore.js")):"function"==typeof define&&define.amd?define(["./GlobalStore.js"],t):"object"==typeof exports?exports["react-hooks-global-states"]=t(require("./GlobalStore.js")):this["react-hooks-global-states"]=t(this["./GlobalStore.js"]);
1
+ var t;t=t=>/******/(()=>{
2
+ /******/"use strict";
3
+ /******/var e={
4
+ /***/778:
5
+ /***/e=>{e.exports=t;
6
+ /***/
7
+ /******/}},o={};
8
+ /************************************************************************/
9
+ /******/
10
+ /******/
11
+ /******/
12
+ /******/
13
+ /******/function r(t){
14
+ /******/
15
+ /******/var n=o[t];
16
+ /******/if(void 0!==n)
17
+ /******/return n.exports;
18
+ /******/
19
+ /******/
20
+ /******/var i=o[t]={
21
+ /******/
22
+ /******/
23
+ /******/exports:{}
24
+ /******/};
25
+ /******/
26
+ /******/
27
+ /******/
28
+ /******/
29
+ /******/
30
+ /******/return e[t](i,i.exports,r),i.exports;
31
+ /******/}
32
+ /******/
33
+ /************************************************************************/var n={};
34
+ /******/return(()=>{var t=n;function e(t){return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},e(t)}function o(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(t){}return(o=function(){return!!t})()}function i(t){return i=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},i(t)}function c(t,e){return c=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},c(t,e)}Object.defineProperty(t,"__esModule",{value:!0}),t.GlobalStoreAbstract=void 0;var u=function(t){function r(){var t;return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,r),(t=function(t,r,n){return r=i(r),function(t,o){if(o&&("object"==e(o)||"function"==typeof o))return o;if(void 0!==o)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(t,o()?Reflect.construct(r,n||[],i(t).constructor):r.apply(t,n))}(this,r,arguments)).onInit=function(e){t.onInitialize(e)},t.onStateChanged=function(e){t.onChange(e)},t}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&c(t,e)}(r,t),n=r,Object.defineProperty(n,"prototype",{writable:!1}),n;var n}(r(778).GlobalStore);
35
+ /**
36
+ * @description
37
+ * Use this class to extends the capabilities of the GlobalStore.
38
+ * by implementing the abstract methods onInitialize and onChange.
39
+ * You can use this class to create a store with async storage.
40
+ */t.GlobalStoreAbstract=u,t.default=u})(),n;
41
+ /******/})(),"object"==typeof exports&&"object"==typeof module?module.exports=t(require("./GlobalStore.js")):"function"==typeof define&&define.amd?define(["./GlobalStore.js"],t):"object"==typeof exports?exports["react-hooks-global-states"]=t(require("./GlobalStore.js")):this["react-hooks-global-states"]=t(this["./GlobalStore.js"]);
package/README.md CHANGED
@@ -43,7 +43,7 @@ React Hooks Global States includes a dedicated, `devTools extension` to streamli
43
43
  Define a **global state** in **one line**:
44
44
 
45
45
  ```tsx
46
- import { createGlobalState } from 'react-hooks-global-states/createGlobalState';
46
+ import createGlobalState from 'react-hooks-global-states/createGlobalState';
47
47
  export const useCount = createGlobalState(0);
48
48
  ```
49
49
 
@@ -86,7 +86,7 @@ You can also add **dependencies** to a selector. This is useful when you want to
86
86
  ```tsx
87
87
  const [contacts] = useContacts(
88
88
  (state) => state.entities.filter((item) => item.name.includes(filter)),
89
- [filter]
89
+ [filter],
90
90
  );
91
91
  ```
92
92
 
@@ -126,19 +126,19 @@ You can still **use dependencies** inside a selector hook:
126
126
  ```tsx
127
127
  const [filteredContacts] = useContactsArray(
128
128
  (contacts) => contacts.filter((c) => c.name.includes(filter)),
129
- [filter]
129
+ [filter],
130
130
  );
131
131
  ```
132
132
 
133
133
  #### βœ… Selector hooks share the same state mutator
134
134
 
135
- The **stateMutator remains the same** across all derived selectors, meaning actions and setState functions stay consistent.
135
+ The **state api is stable across renders** meaning actions and setState functions stay consistent.
136
136
 
137
137
  ```tsx
138
- const [actions1] = useContactsArray();
139
- const [actions2] = useContactsCount();
138
+ const [, setState1] = useContactsArray();
139
+ const [contacts] = useContactsCount();
140
140
 
141
- console.log(actions1 === actions2); // true
141
+ console.log(setState1 === useContacts.setState); // true
142
142
  ```
143
143
 
144
144
  ---
@@ -164,7 +164,7 @@ export const useContacts = createGlobalState(
164
164
  };
165
165
  },
166
166
  },
167
- }
167
+ },
168
168
  );
169
169
  ```
170
170
 
@@ -178,17 +178,17 @@ const [filter, { setFilter }] = useContacts();
178
178
 
179
179
  ## 🌍 Accessing Global State Outside Components
180
180
 
181
- Use `stateControls()` to **retrieve or update state outside React components**:
181
+ You can access and manipulate global without hooks, useful for non-component code like services or utilities.
182
+ Or for non reactive components.
182
183
 
183
184
  ```tsx
184
- const [contactsRetriever, contactsApi] = useContacts.stateControls();
185
- console.log(contactsRetriever()); // Retrieves the current state
185
+ console.log(useContacts.getState()); // Retrieves the current state
186
186
  ```
187
187
 
188
188
  #### βœ… Subscribe to changes
189
189
 
190
190
  ```tsx
191
- const unsubscribe = contactsRetriever((state) => {
191
+ const unsubscribe = useContacts.subscribe((state) => {
192
192
  console.log('State updated:', state);
193
193
  });
194
194
  ```
@@ -199,11 +199,11 @@ const unsubscribe = contactsRetriever((state) => {
199
199
  const useSelectedContact = createGlobalState(null, {
200
200
  callbacks: {
201
201
  onInit: ({ setState, getState }) => {
202
- contactsRetriever(
202
+ useContacts.subscribe(
203
203
  (state) => state.contacts,
204
204
  (contacts) => {
205
205
  if (!contacts.has(getState())) setState(null);
206
- }
206
+ },
207
207
  );
208
208
  },
209
209
  },
@@ -220,8 +220,29 @@ const useSelectedContact = createGlobalState(null, {
220
220
  ### πŸ“Œ Creating a Context
221
221
 
222
222
  ```tsx
223
- import { createContext } from 'react-global-state-hooks/createContext';
224
- export const [useCounterContext, CounterProvider] = createContext(0);
223
+ import createContext from 'react-global-state-hooks/createContext';
224
+
225
+ export const counter = createContext(0);
226
+
227
+ export const App = () => {
228
+ return (
229
+ <counter.Provider>
230
+ <MyComponent />
231
+ </counter.Provider>
232
+ );
233
+ };
234
+
235
+ export const Component = () => {
236
+ const [count, setCount] = counter.use();
237
+
238
+ return <Button onClick={() => setCount((c) => c + 1)}>{count}</Button>;
239
+ };
240
+
241
+ export const Component2 = () => {
242
+ const [count, setCount] = counter.use.api(); // non reactive access to the context api
243
+
244
+ return <Button onClick={() => setCount((c) => c + 1)}>{count}</Button>;
245
+ };
225
246
  ```
226
247
 
227
248
  Wrap your app:
@@ -266,12 +287,11 @@ const unsubscribe = counterLogs((message) => {
266
287
  ### πŸ“Œ Using Observables Inside Context
267
288
 
268
289
  ```tsx
269
- export const [useStateControls, useObservableBuilder] = useCounterContext.stateControls();
270
- const createObservable = useObservableBuilder();
271
290
  useEffect(() => {
272
- const unsubscribe = createObservable((count) => {
291
+ const unsubscribe = useCounterContext.subscribe((count) => {
273
292
  console.log(`Updated count: ${count}`);
274
293
  });
294
+
275
295
  return unsubscribe;
276
296
  }, []);
277
297
  ```
@@ -283,12 +303,11 @@ useEffect(() => {
283
303
  | Feature | `createGlobalState` | `createContext` |
284
304
  | ---------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
285
305
  | **Scope** | Available globally across the entire app | Scoped to the Provider where it’s used |
286
- | **How to Use** | `const useCount = createGlobalState(0)` | `const [useCountContext, Provider] = createContext(0)` |
287
- | **createSelectorHook** | `useCount.createSelectorHook` | `useCountContext.createSelectorHook` |
306
+ | **How to Use** | `const useCount = createGlobalState(0)` | `const counter = createContext(0); counter.Provider, counter.use()` |
307
+ | **createSelectorHook** | `useCount.createSelectorHook` | `counter.use.createSelectorHook()` |
288
308
  | **inline selectors?** | βœ… Supported | βœ… Supported |
289
309
  | **Custom Actions** | βœ… Supported | βœ… Supported |
290
- | **Observables** | `useCount.createObservable` | `const [, useObservableBuilder] = useCountContext.stateControls()` |
291
- | **State Controls** | `useCount.stateControls()` | `const [useStateControls] = useCountContext.stateControls()` |
310
+ | **Observables** | `useCount.createObservable` | `counter.api().createObservable()` |
292
311
  | **Best For** | Global app state (auth, settings, cache) | Scoped module state, reusable component state, or state shared between child components without being fully global |
293
312
 
294
313
  ## πŸ”„ Lifecycle Methods
@@ -310,7 +329,7 @@ const useData = createGlobalState(
310
329
  return state.value === previousState.value;
311
330
  },
312
331
  },
313
- }
332
+ },
314
333
  );
315
334
  ```
316
335