Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions crates/bindings-typescript/src/react/useTable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ export interface UseTableCallbacks<RowType> {
onInsert?: (row: RowType) => void;
onDelete?: (row: RowType) => void;
onUpdate?: (oldRow: RowType, newRow: RowType) => void;
/** Whether the subscription is active. Defaults to `true`. */
enabled?: boolean;
}

type MembershipChange = 'enter' | 'leave' | 'stayIn' | 'stayOut';
Expand Down Expand Up @@ -67,6 +69,7 @@ export function useTable<TableDef extends UntypedTableDef>(
callbacks?: UseTableCallbacks<Prettify<RowType<TableDef>>>
): [readonly Prettify<RowType<TableDef>>[], boolean] {
type UseTableRowType = RowType<TableDef>;
const enabled = callbacks?.enabled ?? true;
const accessorName = getQueryAccessorName(query);
const whereExpr = getQueryWhereClause(query);

Expand All @@ -93,6 +96,9 @@ export function useTable<TableDef extends UntypedTableDef>(
readonly Prettify<UseTableRowType>[],
boolean,
] => {
if (!enabled) {
return [[], true];
}
const connection = connectionState.getConnection();
if (!connection) {
return [[], false];
Expand All @@ -107,7 +113,7 @@ export function useTable<TableDef extends UntypedTableDef>(
// TODO: investigating refactoring so that this is no longer necessary, as we have had genuine bugs with missed deps.
// See https://github.com/clockworklabs/SpacetimeDB/pull/4580.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [connectionState, accessorName, querySql, subscribeApplied]);
}, [connectionState, accessorName, querySql, subscribeApplied, enabled]);

// Invalidate the cached snapshot when computeSnapshot changes (e.g. when
// subscribeApplied flips to true) so getSnapshot() recomputes on the next
Expand All @@ -117,6 +123,10 @@ export function useTable<TableDef extends UntypedTableDef>(
}, [computeSnapshot]);

useEffect(() => {
if (!enabled) {
setSubscribeApplied(false);
return;
}
const connection = connectionState.getConnection()!;
if (connectionState.isActive && connection) {
const cancel = connection
Expand All @@ -129,10 +139,14 @@ export function useTable<TableDef extends UntypedTableDef>(
cancel.unsubscribe();
};
}
}, [querySql, connectionState.isActive, connectionState]);
}, [querySql, connectionState.isActive, connectionState, enabled]);

const subscribe = useCallback(
(onStoreChange: () => void) => {
if (!enabled) {
return () => {};
}

const onInsert = (
ctx: EventContextInterface<UntypedRemoteModule>,
row: any
Expand Down Expand Up @@ -218,6 +232,7 @@ export function useTable<TableDef extends UntypedTableDef>(
callbacks?.onDelete,
callbacks?.onInsert,
callbacks?.onUpdate,
enabled,
]
);

Expand Down