All files / src/components/EditableTable CustomCellEditor.tsx

100% Statements 26/26
93.75% Branches 15/16
100% Functions 6/6
100% Lines 26/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65                        3x 12x 12x 12x 12x 5x 5x 5x       8x 12x 2x 1x 1x     12x 5x 1x   4x 4x 4x 4x 3x 2x     1x   4x 3x         12x                            
import { useEffect, useRef, useState } from 'react';
 
import { MRT_Cell, MRT_TableInstance } from 'material-react-table';
 
import type { ColumnEditConfig } from '.';
 
type Props<TData extends Record<string, any>> = {
  cell: MRT_Cell<TData>;
  table: MRT_TableInstance<TData>;
  config: ColumnEditConfig<TData>;
};
 
const CustomCellEditor = <TData extends Record<string, any>>({ cell, table, config }: Props<TData>) => {
  const [isSaving, setIsSaving] = useState(false);
  const finished = useRef(false);
  const mounted = useRef(true);
  useEffect(() => {
    mounted.current = true;
    return () => {
      mounted.current = false;
    };
  }, []);
 
  const isCurrent = () => mounted.current && table.getState().editingCell?.id === cell.id;
  const cancel = () => {
    if (!finished.current && isCurrent()) {
      finished.current = true;
      table.setEditingCell(null);
    }
  };
  const save = async (value: unknown) => {
    if (finished.current || !isCurrent()) {
      return;
    }
    finished.current = true;
    setIsSaving(true);
    try {
      await config.onSave?.(cell.row.original, value, cell.column.id);
      if (isCurrent()) {
        table.setEditingCell(null);
      }
    } catch {
      finished.current = false;
    } finally {
      if (mounted.current) {
        setIsSaving(false);
      }
    }
  };
 
  return (
    config.customEditComponent?.({
      cell,
      row: cell.row,
      column: cell.column,
      table,
      save,
      cancel,
      isSaving,
    }) ?? null
  );
};
 
export default CustomCellEditor;