I am trying to allow users to update date and also time fields when clicking on the field.
I have tried a number of the different properties offered by MUI, but nothing is letting the values stick. Now, I am getting an error immediately when clicking the data cell and it removes the table from the page.
// This section will help you update a record by id.
recordRoutes.route('/record/:id').put(function (req, res) {
let db_connect = dbo.getDb();
let myquery = { _id: ObjectId(req.params.id) };
let newvalues = {
$set: {
// Include the date property in the newvalues object
date: req.body.date,
time: req.body.time,
activity: req.body.activity,
},
};
db_connect.collection('records').updateOne(myquery, newvalues, function (err, result) {
if (err) throw err;
console.log('1 document updated');
res.json(result);
});
});
<DataGrid
getCellClassName={(params) => {
if (params.field === 'date' || params.field === 'time') {
return '';
}
return params.value === 'Walk'
? 'walk'
: params.value === 'Meal'
? 'meal'
: params.value === 'Potty'
? 'potty'
: 'medication';
}}
initialState={{
sorting: {
sortModel: [{ field: 'date', sort: 'desc' }],
},
}}
components={{ Toolbar: GridToolbar }}
getRowId={(row) => row._id}
experimentalFeatures={{ newEditingApi: true }}
rows={tableData}
columns={columns}
processRowUpdate={processRowUpdate}
onProcessRowUpdateError={handleProcessRowUpdateError}
onCellValueChanged={valueSetter}
pageSize={pageSize}
onPageSizeChange={(newPageSize) => setPageSize(newPageSize)}
rowsPerPageOptions={[5, 10, 15]}
valueSetter={valueSetter}
rowHeight={60}
header
sx={{
backgroundColor: 'white',
borderRadius: 2,
padding: 2,
margin: 2,
overflow: 'hidden',
boxShadow: (theme) => theme.customShadows.z8,
':hover': {
boxShadow: (theme) => theme.customShadows.z16,
header: { backgroundColor: 'white' },
},
':active': { boxShadow: (theme) => theme.customShadows.z24 },
}}
/>
useEffect(() => {
const timer = setInterval(() => {
fetch('http://localhost:3000/record/')
.then((data) => data.json())
.then((data) =>
setTableData(
data.map((record) => ({
...record,
id: record._id, // Add the 'id' property to each record
}))
)
);
}, 500);
return () => clearInterval(timer);
}, []);
const useFakeMutation = () => {
return React.useCallback(
(user) =>
new Promise((resolve, reject) =>
setTimeout(() => {
if (user.name?.trim() === '') {
reject(new Error("Error while saving user: name can't be empty."));
} else {
resolve({ ...user, name: user.name?.toUpperCase() });
}
}, 200)
),
[]
);
};
const mutateRow = useFakeMutation();
const [snackbar, setSnackbar] = React.useState(null);
const handleCloseSnackbar = () => setSnackbar(null);
const processRowUpdate = React.useCallback(
async (newRow) => {
// Make a put request to the server with the new data
// Include the date property in the newRow object
await fetch(`http://localhost:3000/record/${newRow.id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
date: newRow.date,
time: newRow.time,
activity: newRow.activity,
}),
}).catch((error) => {
window.alert(error);
});
const response = await mutateRow(newRow);
setSnackbar({ children: 'User successfully saved', severity: 'success' });
return response;
},
[mutateRow]
);
const valueSetter = (newValue, rowData) => {
return {
...rowData,
date: newValue, // Update the 'date' property in the row data
};
};
const columns = [
{
field: 'date',
headerName: 'Date',
width: 400,
type: 'dateTime',
flex: 1,
editable: true,
valueSetter: (newValue, oldValue, newRow) => {
if (newValue === oldValue) {
return false; // Return false to cancel the change.
}
// Update the row with the new value.
newRow.date = newValue;
// Return true to signal that the value has been set.
return true;
},
},
{
field: 'time',
headerName: 'Time',
width: 400,
type: 'dateTime',
flex: 1,
editable: true,
},
{ field: 'activity', headerName: 'Activity', width: 200, type: 'number', align: 'center', flex: 0 },
];
const handleProcessRowUpdateError = React.useCallback((error) => {
setSnackbar({ children: error.message, severity: 'error' });
}, []);
I’d also like to add that I am getting a 404 error when trying to access the PUT method from both postman and also the console.