import * as React from "react"; import { FieldListProps } from "./FieldList"; interface FieldListProviderProps extends Omit { setData: React.Dispatch>>>; } type FieldListContext = { addListItem: ( rowId?: string | number, itemToAdd?: Record ) => void; removeListItem: (rowIndex: number) => void; }; export const Context = React.createContext(null); export const FieldListProvider = ({ onAddItem, children, data, pathToUniqueKey, onRemoveItem, setData }: FieldListProviderProps) => { const addListItem = ( rowId?: string | number, itemToAdd?: Record ) => { const rowToAdd = itemToAdd || Object.keys(data[0] || {}).reduce( (acc, curr) => ((acc[curr] = ""), acc), {} ); if (pathToUniqueKey && !rowToAdd[pathToUniqueKey]) { rowToAdd[pathToUniqueKey] = rowId || data.length; } if (onAddItem) { onAddItem(rowToAdd); } else { setData([...data, rowToAdd]); } }; const removeListItem = (rowIndex: number) => { if (onRemoveItem) { const handleRemove = onRemoveItem(rowIndex); handleRemove(); } setData(data.filter((_, i) => rowIndex !== i)); }; return ( {children} ); };