@objectstack/client-react 0.6.1

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.
@@ -0,0 +1,593 @@
1
+ /**
2
+ * Data Query Hooks
3
+ *
4
+ * React hooks for querying and mutating ObjectStack data
5
+ */
6
+
7
+ import { useState, useEffect, useCallback, useRef } from 'react';
8
+ import { QueryAST, FilterCondition } from '@objectstack/spec/data';
9
+ import { PaginatedResult } from '@objectstack/client';
10
+ import { useClient } from './context';
11
+
12
+ /**
13
+ * Query options for useQuery hook
14
+ */
15
+ export interface UseQueryOptions<T = any> {
16
+ /** Query AST or simplified query options */
17
+ query?: Partial<QueryAST>;
18
+ /** Simple field selection */
19
+ select?: string[];
20
+ /** Simple filters */
21
+ filters?: FilterCondition;
22
+ /** Sort configuration */
23
+ sort?: string | string[];
24
+ /** Limit results */
25
+ top?: number;
26
+ /** Skip results (for pagination) */
27
+ skip?: number;
28
+ /** Enable/disable automatic query execution */
29
+ enabled?: boolean;
30
+ /** Refetch interval in milliseconds */
31
+ refetchInterval?: number;
32
+ /** Callback on successful query */
33
+ onSuccess?: (data: PaginatedResult<T>) => void;
34
+ /** Callback on error */
35
+ onError?: (error: Error) => void;
36
+ }
37
+
38
+ /**
39
+ * Query result for useQuery hook
40
+ */
41
+ export interface UseQueryResult<T = any> {
42
+ /** Query result data */
43
+ data: PaginatedResult<T> | null;
44
+ /** Loading state */
45
+ isLoading: boolean;
46
+ /** Error state */
47
+ error: Error | null;
48
+ /** Refetch the query */
49
+ refetch: () => Promise<void>;
50
+ /** Is currently refetching */
51
+ isRefetching: boolean;
52
+ }
53
+
54
+ /**
55
+ * Hook for querying ObjectStack data with automatic caching and refetching
56
+ *
57
+ * @example
58
+ * ```tsx
59
+ * function TaskList() {
60
+ * const { data, isLoading, error, refetch } = useQuery('todo_task', {
61
+ * select: ['id', 'subject', 'priority'],
62
+ * sort: ['-created_at'],
63
+ * top: 20
64
+ * });
65
+ *
66
+ * if (isLoading) return <div>Loading...</div>;
67
+ * if (error) return <div>Error: {error.message}</div>;
68
+ *
69
+ * return (
70
+ * <div>
71
+ * {data?.value.map(task => (
72
+ * <div key={task.id}>{task.subject}</div>
73
+ * ))}
74
+ * </div>
75
+ * );
76
+ * }
77
+ * ```
78
+ */
79
+ export function useQuery<T = any>(
80
+ object: string,
81
+ options: UseQueryOptions<T> = {}
82
+ ): UseQueryResult<T> {
83
+ const client = useClient();
84
+ const [data, setData] = useState<PaginatedResult<T> | null>(null);
85
+ const [isLoading, setIsLoading] = useState(true);
86
+ const [isRefetching, setIsRefetching] = useState(false);
87
+ const [error, setError] = useState<Error | null>(null);
88
+ const intervalRef = useRef<NodeJS.Timeout>();
89
+
90
+ const {
91
+ query,
92
+ select,
93
+ filters,
94
+ sort,
95
+ top,
96
+ skip,
97
+ enabled = true,
98
+ refetchInterval,
99
+ onSuccess,
100
+ onError
101
+ } = options;
102
+
103
+ const fetchData = useCallback(async (isRefetch = false) => {
104
+ if (!enabled) return;
105
+
106
+ try {
107
+ if (isRefetch) {
108
+ setIsRefetching(true);
109
+ } else {
110
+ setIsLoading(true);
111
+ }
112
+ setError(null);
113
+
114
+ let result: PaginatedResult<T>;
115
+
116
+ if (query) {
117
+ // Use advanced query API
118
+ result = await client.data.query<T>(object, query);
119
+ } else {
120
+ // Use simplified find API
121
+ result = await client.data.find<T>(object, {
122
+ select,
123
+ filters: filters as any,
124
+ sort,
125
+ top,
126
+ skip
127
+ });
128
+ }
129
+
130
+ setData(result);
131
+ onSuccess?.(result);
132
+ } catch (err) {
133
+ const error = err instanceof Error ? err : new Error('Query failed');
134
+ setError(error);
135
+ onError?.(error);
136
+ } finally {
137
+ setIsLoading(false);
138
+ setIsRefetching(false);
139
+ }
140
+ }, [client, object, query, select, filters, sort, top, skip, enabled, onSuccess, onError]);
141
+
142
+ // Initial fetch and dependency-based refetch
143
+ useEffect(() => {
144
+ fetchData();
145
+ }, [fetchData]);
146
+
147
+ // Setup refetch interval
148
+ useEffect(() => {
149
+ if (refetchInterval && enabled) {
150
+ intervalRef.current = setInterval(() => {
151
+ fetchData(true);
152
+ }, refetchInterval);
153
+
154
+ return () => {
155
+ if (intervalRef.current) {
156
+ clearInterval(intervalRef.current);
157
+ }
158
+ };
159
+ }
160
+ return undefined;
161
+ }, [refetchInterval, enabled, fetchData]);
162
+
163
+ const refetch = useCallback(async () => {
164
+ await fetchData(true);
165
+ }, [fetchData]);
166
+
167
+ return {
168
+ data,
169
+ isLoading,
170
+ error,
171
+ refetch,
172
+ isRefetching
173
+ };
174
+ }
175
+
176
+ /**
177
+ * Mutation options for useMutation hook
178
+ */
179
+ export interface UseMutationOptions<TData = any, TVariables = any> {
180
+ /** Callback on successful mutation */
181
+ onSuccess?: (data: TData, variables: TVariables) => void;
182
+ /** Callback on error */
183
+ onError?: (error: Error, variables: TVariables) => void;
184
+ /** Callback when mutation is settled (success or error) */
185
+ onSettled?: (data: TData | undefined, error: Error | null, variables: TVariables) => void;
186
+ }
187
+
188
+ /**
189
+ * Mutation result for useMutation hook
190
+ */
191
+ export interface UseMutationResult<TData = any, TVariables = any> {
192
+ /** Execute the mutation */
193
+ mutate: (variables: TVariables) => Promise<TData>;
194
+ /** Async version of mutate that throws errors */
195
+ mutateAsync: (variables: TVariables) => Promise<TData>;
196
+ /** Mutation result data */
197
+ data: TData | null;
198
+ /** Loading state */
199
+ isLoading: boolean;
200
+ /** Error state */
201
+ error: Error | null;
202
+ /** Reset mutation state */
203
+ reset: () => void;
204
+ }
205
+
206
+ /**
207
+ * Hook for creating, updating, or deleting ObjectStack data
208
+ *
209
+ * @example
210
+ * ```tsx
211
+ * function CreateTaskForm() {
212
+ * const { mutate, isLoading, error } = useMutation('todo_task', 'create', {
213
+ * onSuccess: (data) => {
214
+ * console.log('Task created:', data);
215
+ * }
216
+ * });
217
+ *
218
+ * const handleSubmit = (formData) => {
219
+ * mutate(formData);
220
+ * };
221
+ *
222
+ * return <form onSubmit={handleSubmit}>...</form>;
223
+ * }
224
+ * ```
225
+ */
226
+ export function useMutation<TData = any, TVariables = any>(
227
+ object: string,
228
+ operation: 'create' | 'update' | 'delete' | 'createMany' | 'updateMany' | 'deleteMany',
229
+ options: UseMutationOptions<TData, TVariables> = {}
230
+ ): UseMutationResult<TData, TVariables> {
231
+ const client = useClient();
232
+ const [data, setData] = useState<TData | null>(null);
233
+ const [isLoading, setIsLoading] = useState(false);
234
+ const [error, setError] = useState<Error | null>(null);
235
+
236
+ const { onSuccess, onError, onSettled } = options;
237
+
238
+ const mutateAsync = useCallback(async (variables: TVariables): Promise<TData> => {
239
+ setIsLoading(true);
240
+ setError(null);
241
+
242
+ try {
243
+ let result: TData;
244
+
245
+ switch (operation) {
246
+ case 'create':
247
+ result = await client.data.create<TData>(object, variables as any);
248
+ break;
249
+ case 'update':
250
+ // Expect variables to be { id: string, data: Partial<T> }
251
+ const updateVars = variables as any;
252
+ result = await client.data.update<TData>(object, updateVars.id, updateVars.data);
253
+ break;
254
+ case 'delete':
255
+ // Expect variables to be { id: string }
256
+ const deleteVars = variables as any;
257
+ result = await client.data.delete(object, deleteVars.id) as any;
258
+ break;
259
+ case 'createMany':
260
+ // createMany returns an array, which may not match TData type
261
+ result = await client.data.createMany(object, variables as any) as any;
262
+ break;
263
+ case 'updateMany':
264
+ // Expect variables to be { records: Array<{ id: string, data: Partial<T> }> }
265
+ const updateManyVars = variables as any;
266
+ result = await client.data.updateMany(object, updateManyVars.records, updateManyVars.options) as any;
267
+ break;
268
+ case 'deleteMany':
269
+ // Expect variables to be { ids: string[] }
270
+ const deleteManyVars = variables as any;
271
+ result = await client.data.deleteMany(object, deleteManyVars.ids, deleteManyVars.options) as any;
272
+ break;
273
+ default:
274
+ throw new Error(`Unknown operation: ${operation}`);
275
+ }
276
+
277
+ setData(result);
278
+ onSuccess?.(result, variables);
279
+ onSettled?.(result, null, variables);
280
+
281
+ return result;
282
+ } catch (err) {
283
+ const error = err instanceof Error ? err : new Error('Mutation failed');
284
+ setError(error);
285
+ onError?.(error, variables);
286
+ onSettled?.(undefined, error, variables);
287
+ throw error;
288
+ } finally {
289
+ setIsLoading(false);
290
+ }
291
+ }, [client, object, operation, onSuccess, onError, onSettled]);
292
+
293
+ const mutate = useCallback((variables: TVariables): Promise<TData> => {
294
+ return mutateAsync(variables).catch(() => {
295
+ // Swallow error for non-async version
296
+ // Error is still available in the error state
297
+ return null as any;
298
+ });
299
+ }, [mutateAsync]);
300
+
301
+ const reset = useCallback(() => {
302
+ setData(null);
303
+ setError(null);
304
+ setIsLoading(false);
305
+ }, []);
306
+
307
+ return {
308
+ mutate,
309
+ mutateAsync,
310
+ data,
311
+ isLoading,
312
+ error,
313
+ reset
314
+ };
315
+ }
316
+
317
+ /**
318
+ * Pagination options for usePagination hook
319
+ */
320
+ export interface UsePaginationOptions<T = any> extends Omit<UseQueryOptions<T>, 'top' | 'skip'> {
321
+ /** Page size */
322
+ pageSize?: number;
323
+ /** Initial page (1-based) */
324
+ initialPage?: number;
325
+ }
326
+
327
+ /**
328
+ * Pagination result for usePagination hook
329
+ */
330
+ export interface UsePaginationResult<T = any> extends UseQueryResult<T> {
331
+ /** Current page (1-based) */
332
+ page: number;
333
+ /** Total number of pages */
334
+ totalPages: number;
335
+ /** Total number of records */
336
+ totalCount: number;
337
+ /** Go to next page */
338
+ nextPage: () => void;
339
+ /** Go to previous page */
340
+ previousPage: () => void;
341
+ /** Go to specific page */
342
+ goToPage: (page: number) => void;
343
+ /** Whether there is a next page */
344
+ hasNextPage: boolean;
345
+ /** Whether there is a previous page */
346
+ hasPreviousPage: boolean;
347
+ }
348
+
349
+ /**
350
+ * Hook for paginated data queries
351
+ *
352
+ * @example
353
+ * ```tsx
354
+ * function PaginatedTaskList() {
355
+ * const {
356
+ * data,
357
+ * isLoading,
358
+ * page,
359
+ * totalPages,
360
+ * nextPage,
361
+ * previousPage,
362
+ * hasNextPage,
363
+ * hasPreviousPage
364
+ * } = usePagination('todo_task', {
365
+ * pageSize: 10,
366
+ * sort: ['-created_at']
367
+ * });
368
+ *
369
+ * return (
370
+ * <div>
371
+ * {data?.value.map(task => <div key={task.id}>{task.subject}</div>)}
372
+ * <button onClick={previousPage} disabled={!hasPreviousPage}>Previous</button>
373
+ * <span>Page {page} of {totalPages}</span>
374
+ * <button onClick={nextPage} disabled={!hasNextPage}>Next</button>
375
+ * </div>
376
+ * );
377
+ * }
378
+ * ```
379
+ */
380
+ export function usePagination<T = any>(
381
+ object: string,
382
+ options: UsePaginationOptions<T> = {}
383
+ ): UsePaginationResult<T> {
384
+ const { pageSize = 20, initialPage = 1, ...queryOptions } = options;
385
+ const [page, setPage] = useState(initialPage);
386
+
387
+ const queryResult = useQuery<T>(object, {
388
+ ...queryOptions,
389
+ top: pageSize,
390
+ skip: (page - 1) * pageSize
391
+ });
392
+
393
+ const totalCount = queryResult.data?.count || 0;
394
+ const totalPages = Math.ceil(totalCount / pageSize);
395
+ const hasNextPage = page < totalPages;
396
+ const hasPreviousPage = page > 1;
397
+
398
+ const nextPage = useCallback(() => {
399
+ if (hasNextPage) {
400
+ setPage(p => p + 1);
401
+ }
402
+ }, [hasNextPage]);
403
+
404
+ const previousPage = useCallback(() => {
405
+ if (hasPreviousPage) {
406
+ setPage(p => p - 1);
407
+ }
408
+ }, [hasPreviousPage]);
409
+
410
+ const goToPage = useCallback((newPage: number) => {
411
+ const clampedPage = Math.max(1, Math.min(newPage, totalPages));
412
+ setPage(clampedPage);
413
+ }, [totalPages]);
414
+
415
+ return {
416
+ ...queryResult,
417
+ page,
418
+ totalPages,
419
+ totalCount,
420
+ nextPage,
421
+ previousPage,
422
+ goToPage,
423
+ hasNextPage,
424
+ hasPreviousPage
425
+ };
426
+ }
427
+
428
+ /**
429
+ * Infinite query options for useInfiniteQuery hook
430
+ */
431
+ export interface UseInfiniteQueryOptions<T = any> extends Omit<UseQueryOptions<T>, 'skip'> {
432
+ /** Page size for each fetch */
433
+ pageSize?: number;
434
+ /** Get next page parameter */
435
+ getNextPageParam?: (lastPage: PaginatedResult<T>, allPages: PaginatedResult<T>[]) => number | undefined;
436
+ }
437
+
438
+ /**
439
+ * Infinite query result for useInfiniteQuery hook
440
+ */
441
+ export interface UseInfiniteQueryResult<T = any> {
442
+ /** All pages of data */
443
+ data: PaginatedResult<T>[];
444
+ /** Flattened data from all pages */
445
+ flatData: T[];
446
+ /** Loading state */
447
+ isLoading: boolean;
448
+ /** Error state */
449
+ error: Error | null;
450
+ /** Load the next page */
451
+ fetchNextPage: () => Promise<void>;
452
+ /** Whether there are more pages */
453
+ hasNextPage: boolean;
454
+ /** Is currently fetching next page */
455
+ isFetchingNextPage: boolean;
456
+ /** Refetch all pages */
457
+ refetch: () => Promise<void>;
458
+ }
459
+
460
+ /**
461
+ * Hook for infinite scrolling / load more functionality
462
+ *
463
+ * @example
464
+ * ```tsx
465
+ * function InfiniteTaskList() {
466
+ * const {
467
+ * flatData,
468
+ * isLoading,
469
+ * fetchNextPage,
470
+ * hasNextPage,
471
+ * isFetchingNextPage
472
+ * } = useInfiniteQuery('todo_task', {
473
+ * pageSize: 20,
474
+ * sort: ['-created_at']
475
+ * });
476
+ *
477
+ * return (
478
+ * <div>
479
+ * {flatData.map(task => <div key={task.id}>{task.subject}</div>)}
480
+ * {hasNextPage && (
481
+ * <button onClick={fetchNextPage} disabled={isFetchingNextPage}>
482
+ * {isFetchingNextPage ? 'Loading...' : 'Load More'}
483
+ * </button>
484
+ * )}
485
+ * </div>
486
+ * );
487
+ * }
488
+ * ```
489
+ */
490
+ export function useInfiniteQuery<T = any>(
491
+ object: string,
492
+ options: UseInfiniteQueryOptions<T> = {}
493
+ ): UseInfiniteQueryResult<T> {
494
+ const client = useClient();
495
+ const {
496
+ pageSize = 20,
497
+ // getNextPageParam is reserved for future use
498
+ query,
499
+ select,
500
+ filters,
501
+ sort,
502
+ enabled = true,
503
+ onSuccess,
504
+ onError
505
+ } = options;
506
+
507
+ const [pages, setPages] = useState<PaginatedResult<T>[]>([]);
508
+ const [isLoading, setIsLoading] = useState(true);
509
+ const [isFetchingNextPage, setIsFetchingNextPage] = useState(false);
510
+ const [error, setError] = useState<Error | null>(null);
511
+ const [hasNextPage, setHasNextPage] = useState(true);
512
+
513
+ const fetchPage = useCallback(async (skip: number, isNextPage = false) => {
514
+ try {
515
+ if (isNextPage) {
516
+ setIsFetchingNextPage(true);
517
+ } else {
518
+ setIsLoading(true);
519
+ }
520
+ setError(null);
521
+
522
+ let result: PaginatedResult<T>;
523
+
524
+ if (query) {
525
+ result = await client.data.query<T>(object, {
526
+ ...query,
527
+ limit: pageSize,
528
+ offset: skip
529
+ });
530
+ } else {
531
+ result = await client.data.find<T>(object, {
532
+ select,
533
+ filters: filters as any,
534
+ sort,
535
+ top: pageSize,
536
+ skip
537
+ });
538
+ }
539
+
540
+ if (isNextPage) {
541
+ setPages(prev => [...prev, result]);
542
+ } else {
543
+ setPages([result]);
544
+ }
545
+
546
+ // Determine if there's a next page
547
+ const fetchedCount = result.value.length;
548
+ const hasMore = fetchedCount === pageSize;
549
+ setHasNextPage(hasMore);
550
+
551
+ onSuccess?.(result);
552
+ } catch (err) {
553
+ const error = err instanceof Error ? err : new Error('Query failed');
554
+ setError(error);
555
+ onError?.(error);
556
+ } finally {
557
+ setIsLoading(false);
558
+ setIsFetchingNextPage(false);
559
+ }
560
+ }, [client, object, query, select, filters, sort, pageSize, onSuccess, onError]);
561
+
562
+ // Initial fetch
563
+ useEffect(() => {
564
+ if (enabled) {
565
+ fetchPage(0);
566
+ }
567
+ }, [enabled, fetchPage]);
568
+
569
+ const fetchNextPage = useCallback(async () => {
570
+ if (!hasNextPage || isFetchingNextPage) return;
571
+
572
+ const nextSkip = pages.length * pageSize;
573
+ await fetchPage(nextSkip, true);
574
+ }, [hasNextPage, isFetchingNextPage, pages.length, pageSize, fetchPage]);
575
+
576
+ const refetch = useCallback(async () => {
577
+ setPages([]);
578
+ await fetchPage(0);
579
+ }, [fetchPage]);
580
+
581
+ const flatData = pages.flatMap(page => page.value);
582
+
583
+ return {
584
+ data: pages,
585
+ flatData,
586
+ isLoading,
587
+ error,
588
+ fetchNextPage,
589
+ hasNextPage,
590
+ isFetchingNextPage,
591
+ refetch
592
+ };
593
+ }
package/src/index.tsx ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * @objectstack/client-react
3
+ *
4
+ * React hooks for ObjectStack Client SDK
5
+ *
6
+ * Provides type-safe React hooks for:
7
+ * - Data queries (useQuery, useMutation, usePagination, useInfiniteQuery)
8
+ * - Metadata access (useObject, useView, useFields, useMetadata)
9
+ * - Client context (ObjectStackProvider, useClient)
10
+ */
11
+
12
+ // Context & Provider
13
+ export {
14
+ ObjectStackProvider,
15
+ ObjectStackContext,
16
+ useClient,
17
+ type ObjectStackProviderProps
18
+ } from './context';
19
+
20
+ // Data Hooks
21
+ export {
22
+ useQuery,
23
+ useMutation,
24
+ usePagination,
25
+ useInfiniteQuery,
26
+ type UseQueryOptions,
27
+ type UseQueryResult,
28
+ type UseMutationOptions,
29
+ type UseMutationResult,
30
+ type UsePaginationOptions,
31
+ type UsePaginationResult,
32
+ type UseInfiniteQueryOptions,
33
+ type UseInfiniteQueryResult
34
+ } from './data-hooks';
35
+
36
+ // Metadata Hooks
37
+ export {
38
+ useObject,
39
+ useView,
40
+ useFields,
41
+ useMetadata,
42
+ type UseMetadataOptions,
43
+ type UseMetadataResult
44
+ } from './metadata-hooks';
45
+
46
+ // Re-export ObjectStackClient and types from @objectstack/client
47
+ export { ObjectStackClient, type ClientConfig } from '@objectstack/client';