import React, { useState, useMemo, useEffect, useCallback } from 'react'; import { Button, Intent } from '@blueprintjs/core'; import { FormattedMessage as T, useIntl } from 'react-intl'; import DataTable from 'components/DataTable'; import Icon from 'components/Icon'; import { compose, formattedAmount } from 'utils'; import { AccountsListFieldCell, MoneyFieldCell, InputGroupCell, } from 'components/DataTableCells'; import { omit } from 'lodash'; import withAccounts from 'containers/Accounts/withAccounts'; function ExpenseTable({ // #withAccounts accounts, // #ownPorps onClickRemoveRow, onClickAddNewRow, defaultRow, initialValues, formik: { errors, values, setFieldValue }, }) { const [rows, setRow] = useState([]); const { formatMessage } = useIntl(); useEffect(() => { setRow([ ...initialValues.categories.map((e) => ({ ...e, rowType: 'editor' })), defaultRow, defaultRow, ]); }, [initialValues, defaultRow]); // Handles update datatable data. const handleUpdateData = useCallback( (rowIndex, columnId, value) => { const newRows = rows.map((row, index) => { if (index === rowIndex) { return { ...rows[rowIndex], [columnId]: value }; } return { ...row }; }); setRow(newRows); setFieldValue( 'categories', newRows.map((row) => ({ ...omit(row, ['rowType']), })), ); }, [rows, setFieldValue], ); // Handles click remove datatable row. const handleRemoveRow = useCallback( (rowIndex) => { const removeIndex = parseInt(rowIndex, 10); const newRows = rows.filter((row, index) => index !== removeIndex); setRow([...newRows]); setFieldValue( 'categories', newRows .filter((row) => row.rowType === 'editor') .map((row) => ({ ...omit(row, ['rowType']) })), ); onClickRemoveRow && onClickRemoveRow(removeIndex); }, [rows, setFieldValue, onClickRemoveRow], ); // Actions cell renderer. const ActionsCellRenderer = ({ row: { index }, column: { id }, cell: { value: initialValue }, data, payload, }) => { if (data.length <= index + 2) { return ''; } const onClickRemoveRole = () => { payload.removeRow(index); }; return ( ); } export default compose( withAccounts(({ accounts }) => ({ accounts, })), )(ExpenseTable);