react-shared-states 1.0.6 → 1.0.8

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/.editorconfig CHANGED
@@ -6,4 +6,10 @@ root = true
6
6
  indent_size = 4
7
7
 
8
8
  [*.md]
9
+ indent_size = 2
10
+
11
+ [*.yml]
12
+ indent_size = 2
13
+
14
+ [*.json]
9
15
  indent_size = 2
package/README.md CHANGED
@@ -48,7 +48,6 @@ function B(){
48
48
  }
49
49
 
50
50
  function App() {
51
-
52
51
  return (
53
52
  <>
54
53
  <A/>
@@ -69,7 +68,6 @@ function Scoped(){
69
68
  }
70
69
 
71
70
  function App() {
72
-
73
71
  return (
74
72
  <>
75
73
  <A/>
@@ -82,6 +80,33 @@ function App() {
82
80
  }
83
81
  ```
84
82
 
83
+ ---
84
+
85
+ > **Tip:** For large apps, you can also use `createSharedState(initialValue, scopeName?)` to create and export reusable shared states. If you specify a `scopeName`, the state will always be found in that scope; otherwise, it defaults to global. This helps avoid key collisions and ensures type safety.
86
+
87
+ ```tsx
88
+ import { useSharedState } from 'react-shared-states';
89
+ export const sharedCounter = createSharedState(0);
90
+
91
+ function A(){
92
+ const [count, setCount] = useSharedState(sharedCounter);
93
+ return <button onClick={()=>setCount(c=>c+1)}>A {count}</button>;
94
+ }
95
+ function B(){
96
+ const [count] = useSharedState(sharedCounter);
97
+ return <span>B sees {count}</span>;
98
+ }
99
+
100
+ function App() {
101
+ return (
102
+ <>
103
+ <A/>
104
+ <B/>
105
+ </>
106
+ )
107
+ }
108
+ ```
109
+
85
110
  Override / jump to a named scope explicitly:
86
111
  ```tsx
87
112
  useSharedState('counter', 0, 'modal'); // 3rd arg is scopeName override
@@ -173,19 +198,22 @@ export default function App(){
173
198
 
174
199
 
175
200
  ## 🧠 Core Concepts
176
- | Concept | Summary |
177
- |----------------------|---------------------------------------------------------------------------------------------------------------------------------|
178
- | Global by default | No provider necessary. Same key => shared state. |
179
- | Scoping | Wrap with `SharedStatesProvider` to isolate. Nearest provider wins. |
180
- | Named scopes | `scopeName` prop lets distant providers sync (same name ⇒ same bucket). Unnamed providers auto‑generate a random isolated name. |
181
- | Manual override | Third param in `useSharedState` / `useSharedFunction` / `useSharedSubscription` enforces a specific scope ignoring tree search. |
182
- | Shared functions | Encapsulate async logic: single flight + cached result + `error` + `isLoading` + opt‑in refresh. |
183
- | Shared subscriptions | Real-time data streams: automatic cleanup + shared connections + `error` + `isLoading` + subscription state. |
184
- | Static APIs | Access state/functions/subscriptions outside components (`sharedStatesApi`, `sharedFunctionsApi`, `sharedSubscriptionsApi`). |
201
+ | Concept | Summary |
202
+ |------------------------|---------------------------------------------------------------------------------------------------------------------------------|
203
+ | Global by default | No provider necessary. Same key => shared state. |
204
+ | Scoping | Wrap with `SharedStatesProvider` to isolate. Nearest provider wins. |
205
+ | Named scopes | `scopeName` prop lets distant providers sync (same name ⇒ same bucket). Unnamed providers auto‑generate a random isolated name. |
206
+ | Manual override | Third param in `useSharedState` / `useSharedFunction` / `useSharedSubscription` enforces a specific scope ignoring tree search. |
207
+ | Shared functions | Encapsulate async logic: single flight + cached result + `error` + `isLoading` + opt‑in refresh. |
208
+ | Shared subscriptions | Real-time data streams: automatic cleanup + shared connections + `error` + `isLoading` + subscription state. |
209
+ | Static APIs | Access state/functions/subscriptions outside components (`sharedStatesApi`, `sharedFunctionsApi`, `sharedSubscriptionsApi`). |
210
+ | Static/shared creation | Use `createSharedState`, `createSharedFunction`, `createSharedSubscription` to export reusable, type-safe shared resources. |
185
211
 
186
212
 
187
213
  ## 🏗️ Sharing State (`useSharedState`)
188
- Signature: `const [value, setValue] = useSharedState(key, initialValue, scopeName?);`
214
+ Signature:
215
+ - `const [value, setValue] = useSharedState(key, initialValue, scopeName?)`
216
+ - `const [value, setValue] = useSharedState(sharedStateCreated)`
189
217
 
190
218
  Behavior:
191
219
  * First hook call (per key + scope) seeds with `initialValue`.
@@ -194,35 +222,44 @@ Behavior:
194
222
  * React batching + equality check: listeners fire only when the value reference actually changes.
195
223
 
196
224
  ### Examples
197
- 1. Global theme
225
+ 1. Global theme (recommended for large apps)
198
226
  ```tsx
199
- const [theme, setTheme] = useSharedState('theme', 'light');
227
+ // themeState.ts
228
+ export const themeState = createSharedState('light');
229
+ // In components
230
+ const [theme, setTheme] = useSharedState(themeState);
200
231
  ```
201
232
  2. Isolated wizard progress
202
233
  ```tsx
234
+ const wizardProgress = createSharedState(0);
203
235
  <SharedStatesProvider>
204
236
  <Wizard/>
205
237
  </SharedStatesProvider>
238
+ // In Wizard
239
+ const [step, setStep] = useSharedState(wizardProgress);
206
240
  ```
207
241
  3. Forcing cross‑portal sync
208
242
  ```tsx
243
+ const navState = createSharedState('closed', 'nav');
209
244
  <SharedStatesProvider scopeName="nav" children={<PrimaryNav/>} />
210
245
  <Portal>
211
246
  <SharedStatesProvider scopeName="nav" children={<MobileNav/>} />
212
247
  </Portal>
248
+ // In both navs
249
+ const [navOpen, setNavOpen] = useSharedState(navState);
213
250
  ```
214
251
  4. Overriding nearest provider
215
252
  ```tsx
216
253
  // Even if inside a provider, this explicitly binds to global
217
- const [flag, setFlag] = useSharedState('feature-x-enabled', false, '_global');
254
+ const globalFlag = createSharedState(false, '_global');
255
+ const [flag, setFlag] = useSharedState(globalFlag);
218
256
  ```
219
257
 
220
258
 
221
259
  ## ⚡ Shared Async Functions (`useSharedFunction`)
222
260
  Signature:
223
- ```ts
224
- const { state, trigger, forceTrigger, clear } = useSharedFunction(key, asyncFn, scopeName?);
225
- ```
261
+ - `const { state, trigger, forceTrigger, clear } = useSharedFunction(key, asyncFn, scopeName?)`
262
+ - `const { state, trigger, forceTrigger, clear } = useSharedFunction(sharedFunctionCreated)`
226
263
  `state` shape: `{ results?: T; isLoading: boolean; error?: unknown }`
227
264
 
228
265
  Semantics:
@@ -233,12 +270,12 @@ Semantics:
233
270
 
234
271
  ### Pattern: lazy load on first render
235
272
  ```tsx
273
+ // profileFunction.ts
274
+ export const profileFunction = createSharedFunction((id: string) => fetch(`/api/p/${id}`).then(r=>r.json()));
275
+
236
276
  function Profile({id}:{id:string}){
237
- const { state, trigger } = useSharedFunction(`profile-${id}`, () => fetch(`/api/p/${id}`).then(r=>r.json()));
238
-
239
- if(!state.results && !state.isLoading) trigger();
240
- if(state.isLoading) return <p>Loading...</p>;
241
- return <pre>{JSON.stringify(state.results,null,2)}</pre>
277
+ const { state, trigger } = useSharedFunction(profileFunction);
278
+ // ...same as before
242
279
  }
243
280
  ```
244
281
 
@@ -254,9 +291,8 @@ Perfect for Firebase listeners, WebSocket connections,
254
291
  Server-Sent Events, or any streaming data source that needs cleanup.
255
292
 
256
293
  Signature:
257
- ```ts
258
- const { state, trigger, unsubscribe } = useSharedSubscription(key, subscriber, scopeName?);
259
- ```
294
+ - `const { state, trigger, unsubscribe } = useSharedSubscription(key, subscriber, scopeName?)`
295
+ - `const { state, trigger, unsubscribe } = useSharedSubscription(sharedSubscriptionCreated)`
260
296
 
261
297
  `state` shape: `{ data?: T; isLoading: boolean; error?: unknown; subscribed: boolean }`
262
298
 
@@ -268,36 +304,19 @@ The `subscriber` function receives three callbacks:
268
304
 
269
305
  ### Pattern: Firebase Firestore real-time listener
270
306
  ```tsx
271
- import { useEffect } from 'react';
307
+ // userSubscription.ts
272
308
  import { onSnapshot, doc } from 'firebase/firestore';
273
- import { useSharedSubscription } from 'react-shared-states';
274
- import { db } from './firebase-config'; // your Firebase config
309
+ import { createSharedSubscription } from 'react-shared-states';
310
+ import { db } from './firebase-config';
275
311
 
276
- function UserProfile({ userId }: { userId: string }) {
277
- const { state, trigger, unsubscribe } = useSharedSubscription(
278
- `user-${userId}`,
279
- async (set, onError, onCompletion) => {
280
- const userRef = doc(db, 'users', userId);
281
-
282
- // Set up the real-time listener
283
- const unsubscribe = onSnapshot(
284
- userRef,
285
- (snapshot) => {
286
- if (snapshot.exists()) {
287
- set({ id: snapshot.id, ...snapshot.data() });
288
- } else {
289
- set(null);
290
- }
291
- },
292
- onError,
293
- onCompletion
294
- );
295
-
296
- // Return cleanup function
297
- return unsubscribe;
298
- }
299
- );
312
+ export const userSubscription = createSharedSubscription(
313
+ async (set, onError, onCompletion) => {
314
+ // ...same as before
315
+ }
316
+ );
300
317
 
318
+ function UserProfile({ userId }: { userId: string }) {
319
+ const { state, trigger, unsubscribe } = useSharedSubscription(userSubscription);
301
320
  // Start listening when component mounts
302
321
  useEffect(() => {
303
322
  trigger();
@@ -395,36 +414,62 @@ Subscription semantics:
395
414
 
396
415
 
397
416
  ## 🛰️ Static APIs (outside React)
417
+ ## 🏛️ Static/Global Shared Resource Creation
418
+
419
+ For large apps, you can create and export shared state, function, or subscription objects for type safety and to avoid key collisions. This pattern is similar to Zustand or Jotai stores:
420
+
421
+ ```ts
422
+ import { createSharedState, createSharedFunction, createSharedSubscription, useSharedState, useSharedFunction, useSharedSubscription } from 'react-shared-states';
423
+
424
+ // Create and export shared resources
425
+ export const counterState = createSharedState(0);
426
+ export const fetchUserFunction = createSharedFunction(() => fetch('/api/me').then(r => r.json()));
427
+ export const chatSubscription = createSharedSubscription((set, onError, onCompletion) => {/* ... */});
428
+
429
+ // Use anywhere in your app
430
+ const [count, setCount] = useSharedState(counterState);
431
+ const { state, trigger } = useSharedFunction(fetchUserFunction);
432
+ const { state, trigger, unsubscribe } = useSharedSubscription(chatSubscription);
433
+ ```
398
434
  Useful for SSR hydration, event listeners, debugging, imperative workflows.
399
435
 
400
436
  ```ts
401
437
  import { sharedStatesApi, sharedFunctionsApi, sharedSubscriptionsApi } from 'react-shared-states';
402
438
 
403
- // Preload state
439
+ // Preload state (global scope by default)
404
440
  sharedStatesApi.set('bootstrap-data', { user: {...} });
405
441
 
442
+ // Preload state in a named scope
443
+ sharedStatesApi.set('bootstrap-data', { user: {...} }, 'myScope');
444
+
406
445
  // Read later
407
- const user = sharedStatesApi.get('bootstrap-data');
446
+ const user = sharedStatesApi.get('bootstrap-data'); // global
447
+ const userScoped = sharedStatesApi.get('bootstrap-data', 'myScope');
448
+
449
+ // Inspect all (returns nested object: { [scope]: { [key]: value } })
450
+ console.log(sharedStatesApi.getAll());
408
451
 
409
- // Inspect all
410
- console.log(sharedStatesApi.getAll()); // Map with prefixed keys
452
+ // Clear all keys in a scope
453
+ sharedStatesApi.clearScope('myScope');
411
454
 
412
455
  // For shared functions
413
456
  const fnState = sharedFunctionsApi.get('profile-123');
457
+ const fnStateScoped = sharedFunctionsApi.get('profile-123', 'myScope');
414
458
 
415
459
  // For shared subscriptions
416
460
  const subState = sharedSubscriptionsApi.get('live-chat');
461
+ const subStateScoped = sharedSubscriptionsApi.get('live-chat', 'myScope');
417
462
  ```
418
463
 
419
464
  ## API summary:
420
465
 
421
- | API | Methods |
422
- |--------------------------|---------------------------------------------------------------------------------------|
423
- | `sharedStatesApi` | `get(key, scope?)`, `set(key,val,scope?)`, `has`, `clear`, `clearAll`, `getAll()` |
424
- | `sharedFunctionsApi` | `get(key, scope?)` (returns fn state), `set`, `has`, `clear`, `clearAll`, `getAll()` |
425
- | `sharedSubscriptionsApi` | `get(key, scope?)` (returns sub state), `set`, `has`, `clear`, `clearAll`, `getAll()` |
466
+ | API | Methods |
467
+ |--------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------|
468
+ | `sharedStatesApi` | `get(key, scopeName?)`, `set(key, val, scopeName?)`, `has(key, scopeName?)`, `clear(key, scopeName?)`, `clearAll()`, `clearScope(scopeName?)`, `getAll()` |
469
+ | `sharedFunctionsApi` | `get(key, scopeName?)`, `set(key, val, scopeName?)`, `has(key, scopeName?)`, `clear(key, scopeName?)`, `clearAll()`, `clearScope(scopeName?)`, `getAll()` |
470
+ | `sharedSubscriptionsApi` | `get(key, scopeName?)`, `set(key, val, scopeName?)`, `has(key, scopeName?)`, `clear(key, scopeName?)`, `clearAll()`, `clearScope(scopeName?)`, `getAll()` |
426
471
 
427
- `scope` defaults to `"_global"`. Internally keys are stored as `${scope}_${key}`.
472
+ `scopeName` defaults to `"_global"`. Internally, keys are stored as `${scope}//${key}`. The `.getAll()` method returns a nested object: `{ [scope]: { [key]: value } }`.
428
473
 
429
474
 
430
475
  ## 🧩 Scoping Rules Deep Dive
@@ -481,16 +526,25 @@ Currently no built-in Suspense wrappers; wrap `useSharedFunction` yourself if de
481
526
  ### `useSharedState(key, initialValue, scopeName?)`
482
527
  Returns `[value, setValue]`.
483
528
 
529
+ ### `useSharedState(sharedStateCreated)`
530
+ Returns `[value, setValue]`.
531
+
484
532
  ### `useSharedFunction(key, fn, scopeName?)`
485
533
  Returns `{ state, trigger, forceTrigger, clear }`.
486
534
 
535
+ ### `useSharedFunction(sharedFunctionCreated)`
536
+ Returns `{ state, trigger, forceTrigger, clear }`.
537
+
487
538
  ### `useSharedSubscription(key, subscriber, scopeName?)`
488
539
  Returns `{ state, trigger, unsubscribe }`.
489
540
 
541
+ ### `useSharedSubscription(sharedSubscriptionCreated)`
542
+ Returns `{ state, trigger, unsubscribe }`.
543
+
490
544
  ### `<SharedStatesProvider scopeName?>`
491
545
  Wrap children; optional `scopeName` (string). If omitted a random unique one is generated.
492
546
 
493
- ### Static
547
+ ### Static APIs
494
548
  `sharedStatesApi`, `sharedFunctionsApi`, `sharedSubscriptionsApi` (see earlier table).
495
549
 
496
550
 
@@ -1,4 +1,4 @@
1
- import { AFunction, DataMapValue, Prefix } from './types';
1
+ import { AFunction, DataMapValue, Prefix, SharedCreated } from './types';
2
2
  type SharedDataType<T> = DataMapValue & T;
3
3
  export declare abstract class SharedData<T> {
4
4
  data: Map<string, SharedDataType<T>>;
@@ -13,14 +13,50 @@ export declare abstract class SharedData<T> {
13
13
  setValue(key: string, prefix: Prefix, data: T): void;
14
14
  has(key: string, prefix: Prefix): string | undefined;
15
15
  static prefix(key: string, prefix: Prefix): string;
16
+ static extractPrefix(mapKey: string): string[];
16
17
  useEffect(key: string, prefix: Prefix, unsub?: (() => void) | null): void;
17
18
  }
18
- export interface SharedApi<T> {
19
- get: <S extends string = string>(key: S, scopeName: Prefix) => T;
20
- set: <S extends string = string>(key: S, value: T, scopeName: Prefix) => void;
21
- clearAll: () => void;
22
- clear: (key: string, scopeName: Prefix) => void;
23
- has: (key: string, scopeName: Prefix) => boolean;
24
- getAll: () => Map<string, DataMapValue>;
19
+ export declare class SharedApi<T> {
20
+ private sharedData;
21
+ constructor(sharedData: SharedData<T>);
22
+ /**
23
+ * get a value from the shared data
24
+ * @param key
25
+ * @param scopeName
26
+ */
27
+ get<S extends string = string>(key: S, scopeName: Prefix): T;
28
+ /**
29
+ * set a value in the shared data
30
+ * @param key
31
+ * @param value
32
+ * @param scopeName
33
+ */
34
+ set<S extends string = string>(key: S, value: T, scopeName: Prefix): void;
35
+ /**
36
+ * clear all values from the shared data
37
+ */
38
+ clearAll(): void;
39
+ /**
40
+ * clear all values from the shared data in a scope
41
+ * @param scopeName
42
+ */
43
+ clearScope(scopeName?: Prefix): void;
44
+ /**
45
+ * resolve a shared created object to a value
46
+ * @param sharedCreated
47
+ */
48
+ resolve(sharedCreated: SharedCreated): T;
49
+ clear(key: string, scopeName: Prefix): void;
50
+ clear(sharedCreated: SharedCreated): void;
51
+ /**
52
+ * check if a value exists in the shared data
53
+ * @param key
54
+ * @param scopeName
55
+ */
56
+ has(key: string, scopeName?: Prefix): boolean;
57
+ /**
58
+ * get all values from the shared data
59
+ */
60
+ getAll(): Record<string, Record<string, any>>;
25
61
  }
26
62
  export {};
@@ -1,11 +1,12 @@
1
1
  import { PropsWithChildren } from 'react';
2
- import { NonEmptyString } from '../types';
2
+ import { Prefix } from '../types';
3
3
  export interface SharedStatesType {
4
4
  scopeName: string;
5
5
  }
6
- interface SharedStatesProviderProps<T extends string = string> extends PropsWithChildren {
7
- scopeName?: '__global' extends NonEmptyString<T> ? never : NonEmptyString<T>;
6
+ export declare const SharedStatesContext: import('react').Context<SharedStatesType | undefined>;
7
+ interface SharedStatesProviderProps extends PropsWithChildren {
8
+ scopeName?: Prefix;
8
9
  }
9
- export declare const SharedStatesProvider: <T extends string = string>({ children, scopeName }: SharedStatesProviderProps<T>) => import("react/jsx-runtime").JSX.Element;
10
+ export declare const SharedStatesProvider: ({ children, scopeName }: SharedStatesProviderProps) => import("react/jsx-runtime").JSX.Element;
10
11
  export declare const useSharedStatesContext: () => SharedStatesType | undefined;
11
12
  export {};
@@ -1,3 +1,6 @@
1
- export { useSharedState, sharedStatesApi } from './use-shared-state';
2
- export { useSharedFunction, sharedFunctionsApi } from './use-shared-function';
3
- export { useSharedSubscription, sharedSubscriptionsApi } from './use-shared-subscription';
1
+ export { useSharedState, sharedStatesApi, createSharedState, SharedStatesApi } from './use-shared-state';
2
+ export type { SharedStateCreated } from './use-shared-state';
3
+ export { useSharedFunction, sharedFunctionsApi, createSharedFunction, SharedFunctionsApi } from './use-shared-function';
4
+ export type { SharedFunctionStateReturn } from './use-shared-function';
5
+ export { useSharedSubscription, sharedSubscriptionsApi, createSharedSubscription, SharedSubscriptionsApi } from './use-shared-subscription';
6
+ export type { SharedSubscriptionStateReturn } from './use-shared-subscription';
@@ -1,4 +1,4 @@
1
- import { AFunction, Prefix } from '../types';
1
+ import { AFunction, Prefix, SharedCreated } from '../types';
2
2
  import { SharedApi } from '../SharedData';
3
3
  type SharedFunctionsState<T> = {
4
4
  fnState: {
@@ -7,23 +7,21 @@ type SharedFunctionsState<T> = {
7
7
  error?: unknown;
8
8
  };
9
9
  };
10
- export declare class SharedFunctionsApi implements SharedApi<SharedFunctionsState<unknown>> {
10
+ export declare class SharedFunctionsApi extends SharedApi<SharedFunctionsState<unknown>> {
11
11
  get<T, S extends string = string>(key: S, scopeName?: Prefix): T;
12
12
  set<T, S extends string = string>(key: S, fnState: SharedFunctionsState<T>, scopeName?: Prefix): void;
13
- clearAll(): void;
14
- clear(key: string, scopeName?: Prefix): void;
15
- has(key: string, scopeName?: Prefix): boolean;
16
- getAll(): Map<string, import('..').DataMapValue & SharedFunctionsState<unknown>>;
17
13
  }
18
14
  export declare const sharedFunctionsApi: SharedFunctionsApi;
19
- export declare const useSharedFunction: <T, Args extends unknown[], S extends string = string>(key: S, fn: AFunction<T, Args>, scopeName?: Prefix) => {
20
- readonly state: {
21
- results?: T | undefined;
22
- isLoading: boolean;
23
- error?: unknown;
24
- };
15
+ interface SharedFunctionCreated<T, Args extends unknown[]> extends SharedCreated {
16
+ fn: AFunction<T, Args>;
17
+ }
18
+ export declare const createSharedFunction: <T, Args extends unknown[]>(fn: AFunction<T, Args>, scopeName?: Prefix) => SharedFunctionCreated<T, Args>;
19
+ export type SharedFunctionStateReturn<T, Args extends unknown[]> = {
20
+ readonly state: NonNullable<SharedFunctionsState<T>['fnState']>;
25
21
  readonly trigger: (...args: Args) => void;
26
22
  readonly forceTrigger: (...args: Args) => void;
27
23
  readonly clear: () => void;
28
24
  };
25
+ export declare function useSharedFunction<T, Args extends unknown[], S extends string = string>(key: S, fn: AFunction<T, Args>, scopeName?: Prefix): SharedFunctionStateReturn<T, Args>;
26
+ export declare function useSharedFunction<T, Args extends unknown[]>(sharedFunctionCreated: SharedFunctionCreated<T, Args>): SharedFunctionStateReturn<T, Args>;
29
27
  export {};
@@ -1,17 +1,15 @@
1
- import { Prefix } from '../types';
1
+ import { Prefix, SharedCreated } from '../types';
2
2
  import { SharedApi } from '../SharedData';
3
- declare class SharedStatesApi implements SharedApi<{
3
+ export declare class SharedStatesApi extends SharedApi<{
4
4
  value: unknown;
5
5
  }> {
6
6
  get<T, S extends string = string>(key: S, scopeName?: Prefix): T;
7
7
  set<T, S extends string = string>(key: S, value: T, scopeName?: Prefix): void;
8
- clearAll(): void;
9
- clear(key: string, scopeName?: Prefix): void;
10
- has(key: string, scopeName?: Prefix): boolean;
11
- getAll(): Map<string, import('..').DataMapValue & {
12
- value: unknown;
13
- }>;
14
8
  }
15
9
  export declare const sharedStatesApi: SharedStatesApi;
16
- export declare const useSharedState: <T, S extends string = string>(key: S, value: T, scopeName?: Prefix) => readonly [T, (newValueOrCallbackToNewValue: T | ((prev: T) => T)) => void];
17
- export {};
10
+ export interface SharedStateCreated<T> extends SharedCreated {
11
+ initialValue: T;
12
+ }
13
+ export declare const createSharedState: <T>(initialValue: T, scopeName?: Prefix) => SharedStateCreated<T>;
14
+ export declare function useSharedState<T, S extends string>(key: S, initialValue: T, scopeName?: Prefix): readonly [T, (v: T | ((prev: T) => T)) => void];
15
+ export declare function useSharedState<T>(sharedStateCreated: SharedStateCreated<T>): readonly [T, (v: T | ((prev: T) => T)) => void];
@@ -1,4 +1,4 @@
1
- import { PotentialPromise, Prefix } from '../types';
1
+ import { PotentialPromise, Prefix, SharedCreated } from '../types';
2
2
  import { SharedApi } from '../SharedData';
3
3
  type Unsubscribe = () => void;
4
4
  export declare namespace SubscriberEvents {
@@ -16,24 +16,21 @@ type SharedSubscriptionsState<T> = {
16
16
  };
17
17
  unsubscribe?: Unsubscribe | void;
18
18
  };
19
- export declare class SharedSubscriptionsApi implements SharedApi<SharedSubscriptionsState<unknown>> {
19
+ export declare class SharedSubscriptionsApi extends SharedApi<SharedSubscriptionsState<unknown>> {
20
20
  get<T, S extends string = string>(key: S, scopeName?: Prefix): T;
21
21
  set<T, S extends string = string>(key: S, fnState: SharedSubscriptionsState<T>, scopeName?: Prefix): void;
22
- clearAll(): void;
23
- clear(key: string, scopeName?: Prefix): void;
24
- has(key: string, scopeName?: Prefix): boolean;
25
- getAll(): Map<string, import('..').DataMapValue & SharedSubscriptionsState<unknown>>;
26
22
  }
27
23
  export declare const sharedSubscriptionsApi: SharedSubscriptionsApi;
28
- export declare const useSharedSubscription: <T, S extends string = string>(key: S, subscriber: Subscriber<T>, scopeName?: Prefix) => {
29
- readonly state: {
30
- data?: T | undefined;
31
- isLoading: boolean;
32
- error?: unknown;
33
- subscribed: boolean;
34
- };
24
+ interface SharedSubscriptionCreated<T> extends SharedCreated {
25
+ subscriber: Subscriber<T>;
26
+ }
27
+ export declare const createSharedSubscription: <T, Args extends unknown[]>(subscriber: Subscriber<T>, scopeName?: Prefix) => SharedSubscriptionCreated<T>;
28
+ export type SharedSubscriptionStateReturn<T> = {
29
+ readonly state: NonNullable<SharedSubscriptionsState<T>['fnState']>;
35
30
  readonly trigger: () => void;
36
31
  readonly forceTrigger: () => void;
37
32
  readonly unsubscribe: () => void;
38
33
  };
34
+ export declare function useSharedSubscription<T, S extends string = string>(key: S, subscriber: Subscriber<T>, scopeName?: Prefix): SharedSubscriptionStateReturn<T>;
35
+ export declare function useSharedSubscription<T>(sharedSubscriptionCreated: SharedSubscriptionCreated<T>): SharedSubscriptionStateReturn<T>;
39
36
  export {};
@@ -1,3 +1,3 @@
1
- import { NonEmptyString } from '../types';
2
1
  export declare const log: (...args: any[]) => void;
3
- export declare const ensureNonEmptyString: <T extends string>(value: T) => NonEmptyString<T>;
2
+ export declare const ensureNonEmptyString: <X extends string>(value: X) => X;
3
+ export declare const random: () => string;