Skip to content

Commit b9bcc56

Browse files
committed
Enhance regSub function to support string-based computeFn for direct field access in appdb, and add corresponding tests for new functionality.
1 parent a54f50f commit b9bcc56

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

src/subs.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,18 @@ import { mergeTrace, withTrace } from './trace';
1414
const KIND = 'sub';
1515
const KIND_DEPS = 'subDeps';
1616

17-
export function regSub<R>(id: Id, computeFn?: (...values: any[]) => R, depsFn?: (...params: any[]) => SubVector[]): void {
17+
export function regSub<R>(id: Id, computeFn?: ((...values: any[]) => R) | string, depsFn?: (...params: any[]) => SubVector[]): void {
1818
if (hasHandler(KIND, id)) {
1919
consoleLog('warn', `[reflex] Overriding. Subscription '${id}' already registered.`)
2020
}
2121
// If only id is provided, use root subscription logic
2222
if (!computeFn) {
2323
registerHandler(KIND, id, () => getAppDb()[id])
2424
registerHandler(KIND_DEPS, id, () => [])
25+
} else if (typeof computeFn === 'string') {
26+
// String field subscription - access field directly from appdb
27+
registerHandler(KIND, id, () => getAppDb()[computeFn])
28+
registerHandler(KIND_DEPS, id, () => [])
2529
} else {
2630
// Computed subscriptions require depsFn
2731
if (!depsFn) {

src/tests/hook.test.tsx

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ describe('React Hooks', () => {
1313
// Register test subscriptions
1414
regSub('user');
1515
regSub('user-name', (user) => user?.name, () => [['user']]);
16+
regSub('user-email-str', 'userEmail'); // Test string computeFn - simple field name
1617
regSub('todos');
1718
regSub('todos-count', (todos) => (todos || []).length, () => [['todos']]);
1819

@@ -23,6 +24,7 @@ describe('React Hooks', () => {
2324
name: 'John Doe',
2425
2526
},
27+
userEmail: '[email protected]', // For string-based subscription test
2628
todos: [
2729
{ id: 1, text: 'Test todo', completed: false }
2830
]
@@ -63,6 +65,12 @@ describe('React Hooks', () => {
6365
expect(result.current).toBe(1);
6466
});
6567

68+
it('should return string-based subscription value', () => {
69+
const { result } = renderHook(() => useSubscription(['user-email-str']));
70+
71+
expect(result.current).toBe('[email protected]');
72+
});
73+
6674
it('should handle subscription with parameters', () => {
6775
// Register a parameterized subscription
6876
regSub('todo-by-id', (todos, id) => {

0 commit comments

Comments
 (0)