How to handle one to many relationship in TanStack Table (React-Table V8)

Viewed 32

I'm currently trying Tanstack Table, which is a great library!

What I'm trying to do is build up a table that looks like this:

Table that I want

My data come from an API with this type:

type Accounting = {
  category: string;
  total: number; // Sum of all expenses
  expenses: {
    name: string;
    value: number;
  }[];
};

Here is what I've got so far:

const columns = React.useMemo(
    () => [
      columnHelper.accessor("category", {
        header: "Category",
        id: "category",
        cell: (info) => {
          return (
            <>
              {info.row.getCanExpand() && (
                <button
                  {...{
                    onClick: info.row.getToggleExpandedHandler(),
                    style: { cursor: "pointer" },
                    className: "mr-2",
                  }}
                >
                  {info.row.getIsExpanded() ? (
                    <Chevron direction="down" />
                  ) : (
                    <Chevron direction="right" />
                  )}
                </button>
              )}
              {info.getValue()}
            </>
          );
        },
      }),
      columnHelper.accessor("expenses", {
        header: undefined,
        id: "expense-name",
        cell: (info) => {
          // FIXME : this returns a table of objects, I want one row per expense
          return info.getValue();
        },
      }),
      columnHelper.accessor("expenses", {
        aggregationFn: "sum",
        id: "expense-value",
        header: "Expense",
        cell: (info) => {
          // FIXME : this returns a table of objects, I want one row per expense
          return info.getValue();
        },
      }),
    ],
    []
  );

  const grouping = React.useMemo(() => ["category"], []);

  const table = useReactTable({
    data,
    columns,
    state: {
      grouping,
      expanded,
    },
    getExpandedRowModel: getExpandedRowModel(),
    getGroupedRowModel: getGroupedRowModel(),
    getCoreRowModel: getCoreRowModel(),
    onExpandedChange: setExpanded,
    autoResetExpanded: false,
  });

The problem here is that I've got a One-To-Many relationship between one category and multiple expenses for this category.

The above code does not work because tanstack table tries to render a list of objects (a list of expense).

I haven't figure out how Tanstack Table can handle this ? Should I override some sort of render method ? Is Tanstack Table the good choice for this kind of data ?

Respectfully.

0 Answers
Related