Skip to content

Commit

Permalink
Optimize TableColumn component by caching relationship checks
Browse files Browse the repository at this point in the history
- Introduced useMemo to cache `isSource` and `targetCardinality` computations.
  • Loading branch information
hoshinotsuyoshi committed Dec 16, 2024
1 parent 90fae17 commit b1c1aa6
Showing 1 changed file with 23 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { Column, Relationships, Table } from '@liam-hq/db-structure'
import { DiamondFillIcon, DiamondIcon, KeyRound } from '@liam-hq/ui'
import { Handle, Position } from '@xyflow/react'
import clsx from 'clsx'
import { useMemo } from 'react'
import type { FC } from 'react'
import { match } from 'ts-pattern'
import { Cardinality } from './Cardinality'
Expand All @@ -25,15 +26,28 @@ export const TableColumn: FC<TableColumnProps> = ({
}) => {
const handleId = `${table.name}-${column.name}`

const isSource = Object.values(relationships).some(
(relationship) =>
relationship.primaryTableName === table.name &&
relationship.primaryColumnName === column.name,
)
const targetCardinality = Object.values(relationships).find(
({ foreignTableName, foreignColumnName }) =>
foreignTableName === table.name && foreignColumnName === column.name,
)?.cardinality
const { sourceColumns, targetCardinalities } = useMemo(() => {
const sourceColumns: Set<string> = new Set()
const targetCardinalities: Record<string, string | undefined> = {}

for (const relationship of Object.values(relationships)) {
const sourceKey = `${relationship.primaryTableName}-${relationship.primaryColumnName}`
sourceColumns.add(sourceKey)

const targetKey = `${relationship.foreignTableName}-${relationship.foreignColumnName}`
targetCardinalities[targetKey] = relationship.cardinality
}

return { sourceColumns, targetCardinalities }
}, [relationships])

const isSource = useMemo(() => {
return sourceColumns.has(handleId)
}, [sourceColumns, handleId])

const targetCardinality = useMemo(() => {
return targetCardinalities[handleId]
}, [targetCardinalities, handleId])

return (
<li key={column.name} className={styles.columnWrapper}>
Expand Down

0 comments on commit b1c1aa6

Please sign in to comment.