Skip to content

Commit 307f493

Browse files
Merge pull request #27 from HichemTab-tech/add-subscriber-to-api
feat: add subscribe method to SharedValuesManager for listening to shared data changes
2 parents 926c1f6 + a944fcc commit 307f493

File tree

3 files changed

+39
-1
lines changed

3 files changed

+39
-1
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "react-shared-states",
3-
"version": "1.0.14",
3+
"version": "1.0.15",
44
"type": "module",
55
"description": "Global state made as simple as useState, with zero config, built-in async caching, and automatic scoping.",
66
"keywords": [

src/SharedValuesManager.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,4 +282,22 @@ export class SharedValuesApi<T extends SharedValue, V, R = T> {
282282
});
283283
return all;
284284
}
285+
286+
subscribe<S extends string = string>(sharedCreated: SharedCreated, listener: AFunction): void;
287+
subscribe<S extends string = string>(key: S | SharedCreated, listener: AFunction, scopeName?: Prefix) {
288+
let keyStr!: string;
289+
let prefixStr!: string;
290+
if (typeof key === "string") {
291+
keyStr = key;
292+
prefixStr = scopeName || "_global";
293+
}
294+
else{
295+
keyStr = key.key;
296+
prefixStr = key.prefix;
297+
}
298+
this.sharedData.addListener(keyStr, prefixStr, listener);
299+
return () => {
300+
this.sharedData.removeListener(keyStr, prefixStr, listener);
301+
}
302+
}
285303
}

tests/index.test.tsx

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,26 @@ describe('useSharedState', () => {
175175
// Get value after clear (should be initial value because createSharedState re-initializes it)
176176
expect(sharedStatesApi.get(sharedCounter)).toBe(100);
177177
});
178+
179+
it('should be able to subscribe to state changes from api', () => {
180+
const sharedCounter = createSharedState(100);
181+
182+
const subscribeCallback = vi.fn();
183+
184+
act(() => {
185+
sharedStatesApi.subscribe(sharedCounter, () => {
186+
subscribeCallback();
187+
expect(sharedStatesApi.get(sharedCounter)).toBe(200);
188+
});
189+
});
190+
191+
// Update the value
192+
act(() => {
193+
sharedStatesApi.set(sharedCounter,200);
194+
});
195+
196+
expect(subscribeCallback).toHaveBeenCalledTimes(1);
197+
});
178198
});
179199

180200
describe('useSharedFunction', () => {

0 commit comments

Comments
 (0)