Skip to content

Instantly share code, notes, and snippets.

@nestarz
Created April 20, 2023 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nestarz/d902998d9f23321c9bab3728dca58798 to your computer and use it in GitHub Desktop.
Save nestarz/d902998d9f23321c9bab3728dca58798 to your computer and use it in GitHub Desktop.
useTable
import {
type TableOptions,
type TableOptionsResolved,
type RowData,
createTable,
} from "@tanstack/table-core";
export * from "@tanstack/table-core";
import { useComputed, useSignal } from "@preact/signals";
export type Renderable<TProps> = React.ReactNode | React.ComponentType<TProps>;
export function useTable<TData extends RowData>(options: TableOptions<TData>) {
// Create a new table and store it in state
const tableRef = useComputed(() => {
// Compose in the generic options to the user options
const resolvedOptions: TableOptionsResolved<TData> = {
state: {}, // Dummy state
onStateChange: () => {}, // noop
renderFallbackValue: null,
...options,
};
return createTable<TData>(resolvedOptions);
});
// By default, manage table state here using the table's initial state
const state = useSignal(tableRef.peek().initialState);
useComputed(() => {
return tableRef.value.setOptions((prev) => ({
...prev,
...options,
state: {
...state.value,
...options.state,
},
// Similarly, we'll maintain both our internal state and any user-provided
// state.
onStateChange: (updater) => {
state.value = updater;
options.onStateChange?.(updater);
},
}));
}).peek();
return tableRef;
}
export function flexRender<T>(
renderProp: (() => preact.ComponentChild) | string | preact.ComponentChild,
context: T
) {
if (typeof renderProp === "function") return renderProp(context);
return renderProp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment