Created
April 20, 2023 14:27
-
-
Save nestarz/d902998d9f23321c9bab3728dca58798 to your computer and use it in GitHub Desktop.
useTable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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