нужно отправлять данные на бек react+nest+mui

нужно отпавлять данные на бек а именно новые созданные строки использую muidatagrid но данные приходят в таком формате, а нужно что бы приходили с данными которые пользователь заполняет

Request data: {url: 'create-sites', otherParams: {id: 5, serviceId: 1, isNew: true}

import React, { useState } from "react";
import { DataGrid, GridRowModes, GridRowModesModel, GridSlots, GridToolbarContainer } from "@mui/x-data-grid";
import { Button } from "@mui/material";
import AddIcon from '@mui/icons-material/Add';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/DeleteOutlined';
import SaveIcon from '@mui/icons-material/Save';
import CancelIcon from '@mui/icons-material/Close';
import { EditToolbarProps, UpdateTableProps } from "common/types/data";
import { postAsset } from "store/thunks/data";
import { useAppDispatch } from "utils/hook";


const UpdateTableComponent: React.FC<UpdateTableProps> = ({ columns, rows, getSingleAssets, setRows, serviceId, selectedService }) => {
    const [rowModesModel, setRowModesModel] = useState<GridRowModesModel>({});
    const [addedRows, setAddedRows] = useState<any[]>([]);
    const dispatch = useAppDispatch()

    const EditToolbar = (props: EditToolbarProps) => {
        const { setRowModesModel } = props;

        const handleAddClick = () => {
            const id = rows.length > 0 ? Math.max(...rows.map(row => row.id)) + 1 : 1;
            if (serviceId && serviceId.length > 0) {
                const firstServiceId = serviceId[0];
                const newRecord = { id, serviceId: firstServiceId, isNew: true }; 
                setAddedRows(prevAddedRows => [...prevAddedRows, newRecord]);
                setRows(oldRows => [...oldRows, newRecord]); 
                setRowModesModel(oldModel => ({
                    ...oldModel,
                    [id]: { mode: GridRowModes.Edit, fieldToFocus: 'serviceId' },
                }));
            } else {
                console.error("Массив serviceId пустой или не определен");
            }
        };
        

        const handleSaveClick = async () => {
            try {
                await dispatch(postAsset({ url: `${selectedService?.url}`, otherParams: { rows: addedRows } }));
                console.log("Данные успешно сохранены на сервере!");
            } catch (error) {
                console.error("Ошибка при сохранении данных на сервере:", error);
            }
        };
        

        const handleDeleteClick = () => {
            const selectedIds = Object.keys(rowModesModel);
            const newRows = rows.filter(row => !selectedIds.includes(row.id.toString()));
            setRows(() => newRows);
            setRowModesModel((oldModel) => {
                const newModel = { ...oldModel };
                selectedIds.forEach(id => {
                    delete newModel[id];
                });
                return newModel;
            });
        };

        const handleCanelClick = async () => {
            
        }

        const handleEditClick = async () => {
            
        }

        return (
            <GridToolbarContainer>
                <Button color="secondary" startIcon={<AddIcon />} onClick={handleAddClick}/>
                <Button color="secondary" startIcon={<DeleteIcon />} onClick={handleDeleteClick}/>
                <Button color="secondary" startIcon={<SaveIcon />} onClick={handleSaveClick}/>
                <Button color="secondary" startIcon={<CancelIcon />} onClick={handleCanelClick}/>
                <Button color="secondary" startIcon={<EditIcon />} onClick={handleEditClick}/>
            </GridToolbarContainer>
        );
    };

    

    return (
        <div style={{ height: 'auto', width: '100%' }}>
            <DataGrid
                rows={rows}
                columns={columns}
                editMode="row" 
                autoHeight
                rowModesModel={rowModesModel}
                slots={{
                    toolbar: EditToolbar as GridSlots['toolbar'],
                }}
                slotProps={{
                    toolbar: { setRows, setRowModesModel },
                }}
            />
        </div>
    );
};

export default UpdateTableComponent; 
import { useState } from "react";
import { Grid } from "@mui/material";
import { useAppDispatch, useAppSelector } from "utils/hook";
import { getSingleAssets } from "store/thunks/data";
import UpdateTableComponent from "components/update-table";
import { IAssetsService } from "common/types/service";
import MenuService from "components/navigate-service";
import { GridColDef, GridRowModel } from "@mui/x-data-grid";
import { translations } from "utils/helpers/translation";

const ContentComponent = () => {
    const dispatch = useAppDispatch();
    const [selectedService, setSelectedService] = useState<IAssetsService | null>(null);
    const serviceArray: IAssetsService[] = useAppSelector((state) => state.service.service);
    const [columns, setColumns] = useState<GridColDef[]>([]);
    const [rows, setRows] = useState<GridRowModel[]>([]);
    const [serviceId, setServiceId] = useState<(number | undefined)[]>([]);


    const handleServiceSelect = async (selectedService: IAssetsService) => {
        try {
            const data = await dispatch<any>(getSingleAssets({
                url: selectedService.url,
                otherParams: selectedService.otherParams
            }));
    
            setSelectedService(selectedService);
            const services = data.payload.services;

            const serviceIds = services.map((service: any) => service.serviceId);
        
            const columns: GridColDef[] = Object.keys(services[0]).map((field) => ({
                field: field,
                headerName: translations[field] ?? field,
                editMode: "row" ,
                editable: true
            }));
    
            const rows: GridRowModel[] = services.map((service: any, index: number) => ({
                id: index + 1, 
                ...service,
                editMode: "row" ,
                editable: true
            }));
            setServiceId(serviceIds)
            setColumns(columns);
            setRows(rows);
        } catch (error) {
            console.error("Ошибка при загрузке данных для выбранного сервиса:", error);
        }
    };
    

    return (
        <Grid container item xs={12}>
            <Grid container item xs={12} sx={{marginBottom: '20px'}}>
                {serviceArray && <MenuService service={serviceArray} handleServiceSelect={handleServiceSelect} />}
            </Grid>
            <Grid container item xs={12}>
                <UpdateTableComponent 
                    selectedService={selectedService} 
                    getSingleAssets={(params) => dispatch<any>(getSingleAssets(params))}
                    columns={columns}
                    rows={rows}
                    setRows={setRows}
                    serviceId={serviceId}
                    
                />
            </Grid>
        </Grid>
    );
};

export default ContentComponent;

Ответы (0 шт):