cant show data in table using mobx state tree - javascript

I am getting the following error when trying to pass data to material ui table, the table isnt displayed and it crash. Cannot modify '', the object is protected and can only be modified by using an action.
im using typescript and mobx state tree
setTreasurers: flow(function* () {
return self.treasurerData = yield getAllTreasurers();
})
var showTreasurerData = userStore.getTreasurerData
const cloneSheeps = [...showTreasurerData];
return (
<div>
<MaterialTable
title="Tesoreros"
columns={[
{ title: "Email", field: "email" },
{ title: "Cuit", field: "cuit" },
{
title: "Verificado",
field: "verified",
},
]}
data={cloneSheeps}
options={{
sorting: true,
actionsColumnIndex: -1
}}
localization={
{ header: { actions: 'Acciones' } }
}
actions={
[
{
position: "auto",
icon: "done",
tooltip: "Enable User",
onClick: (event, user) => {
var isVerified = true;
ManageTreasurerVerification(user, isVerified)
},
},
{
icon: "cancel",
tooltip: "Disable User",
onClick: (event, user) => {
var isVerified = false;
ManageTreasurerVerification(user, isVerified)
},
},
]}
/>

Related

Can not hide add-button like isEditHiden/isDeleteHiden in material table conditionally

In material-table there is option for hiding edit and delete button conditionally like
<MaterialTable
/// other props
editable={
10 > 5 && {
isEditHidden: () => !10 > 5, // This is condition
isDeleteHidden: () => !10 > 5, // This is condition
onRowAdd: newData =>
}),
onRowUpdate: (newData, oldData) =>
}),
onRowDelete: oldData =>
})
}
}
/>
if isEditHidden or isDeleteHidden is true those button hide. I want to hide add button (beside search icon) also. But i couldn't find any option. Is there any option?
You need to remove editable props and actions props for custom actions if needed and then can use hidden/disabled property to hide/disable action button.
import React from "react";
import MaterialTable from "material-table";
export default function DisableFieldEditable() {
const { useState } = React;
const [columns, setColumns] = useState([
{ title: "Name", field: "name", editable: "onUpdate" },
{ title: "Surname", field: "surname", editable: "never" },
{ title: "Birth Year", field: "birthYear", type: "numeric" },
{
title: "Birth Place",
field: "birthCity",
lookup: { 34: "İstanbul", 63: "Şanlıurfa" }
}
]);
const [data, setData] = useState([
{ name: "Mehmet", surname: "Baran", birthYear: 1987, birthCity: 63 },
{ name: "Zerya Betül", surname: "Baran", birthYear: 2017, birthCity: 34 }
]);
return (
<MaterialTable
title="Disable Field Editable Preview"
columns={columns}
data={data}
actions={[
{
icon: "add",
tooltip: "Add User",
hidden: 10 < 5,
isFreeAction: true,
onClick: (event, rowData) => {
// Perform add operation
}
},
{
icon: 'edit',
tooltip: 'Edit User',
hidden: true,
onClick: (event, rowData) => {
// Perform edit operation
}
},
{
icon: 'delete',
tooltip: 'Delete User',
disabled: true,
onClick: (event, rowData) => {
// Perform delete operation
}
}
]}
/>
);
}

make whole row clickable

i'm new on react(hooks) typescript, trying to learn by doing,
here i have created antd table(which works), on the right side of table is 'Edit' it is clickable and works well, but my question is how to make each row clickable instead of that 'Edit' ? like i could click anywhere on the row and it should take me to its 'Edit' link instead of me clicking just on 'Edit':
import { useTranslation } from "react-i18next";
const { t } = useTranslation();
const columns = [
{
title: t("tilaus.state"),
dataIndex: "state",
key: "state",
render: (value: OrderState) => (
<span className="material-icons">
</span>
),
},
{
title: t("request.parcelId"),
dataIndex: "parcelId",
key: "parcelId",
},
{
title: t("request.date"),
dataIndex: "date",
key: "date",
render: (value: Date) => <div>{value.toLocaleDateString("af-AF")}</div>,
},
{
title: t("request.sender"),
dataIndex: "sender",
key: "sender",
render: (value: CustomerDto) => <div>{value.name}</div>,
},
{
title: t("request.recipient"),
dataIndex: "recipient",
key: "recipient",
render: (value: CustomerDto) => <div>{value.name}</div>,
},
{
title: t("request.price"),
dataIndex: "price",
key: "price",
},
{
title: "",
dataIndex: "id",
key: "id",
render: (value: string) => (
<Link to={"details/" + value}>{t("request.edit")}</Link>
),
},
];
<Table
dataSource={orders}
columns={columns}
pagination={false}
scroll={{ x: true }}
onRow={(record, rowIndex) => {
return {
onClick: (event) => {
handleClick(record);
},
};
}}
/>
Looks like you are using ant.d table. I've grabbed one of the examples and console logged the output. You can find it here: https://codesandbox.io/s/s1xds?file=/index.js to show you how the onclick in the entire row is being triggered.
For your specific thing, you need to change onRow prop. You can't add a Link directly to the row, but you can use history from react-router (if you are using it, docs here) or directly mutate the URL when onclick is called.
So in your case, you'll have to do this:
<Table
dataSource={orders}
columns={columns}
pagination={false}
scroll={{ x: true }}
onRow={(record, rowIndex) => {
return {
onClick: (event) => {
history.push(`/details/${record.id}`);
},
};
}}
/>
or
<Table
dataSource={orders}
columns={columns}
pagination={false}
scroll={{ x: true }}
onRow={(record, rowIndex) => {
return {
onClick: (event) => {
window.location.href = `${window.location.href}/details/${record.id}`
},
};
}}
/>

Grab row data onclick of a field in material-table

import MaterialTable from "material-table";
import ShipmentContext from "../context/ShipmentContext";
const ItemsTable: React.FC = () => {
const shipmentcontext = useContext(ShipmentContext);
const { filtered } = shipmentcontext.State;
return (
<>
<div style={{ width: "100%", overflowY: "hidden" }}>
<MaterialTable
options={{
search: false,
showTitle: false,
toolbar: false,
paging: false,
padding: "dense",
maxBodyHeight: "400px",
minBodyHeight:"400px",
paginationType: "stepped",
tableLayout: "fixed"
}}
columns={[
{ title: "AWB NUMBER", field: "awbno" ,},
{ title: "TRANSPORTER", field: "carrier" },
{ title: "SOURCE", field: "from" },
{ title: "DESTINATION", field: "to" },
{ title: "BRAND", field: "carrier" },
{ title: "START DATE", field: "pickup_date" },
{ title: "ETD", field: "" },
{
title: "STATUS",
field: "current_status",
cellStyle: {
color: "green",
},
},
]}
data={filtered}
/>
</div>
</>
);
};
export default ItemsTable;
I want to gather the data of the field i clicked on the row.As here the data is dynamic i am unable to make an onClick method to grab the object which is clicked in the row.
My table look like this :
table
I want an onClick method which when i click on any AWB number grabs the data of it
You can use the custom render function for that to add a custom onClick handler like this:
columns={[
{ title: "AWB NUMBER", field: "awbno" , render: row => <div onClick={() => console.log(row.awbno)}>{row.awbno}</div>}, // This will be called if this cell is clicked
{ title: "TRANSPORTER", field: "carrier" },
{ title: "SOURCE", field: "from" },
{ title: "DESTINATION", field: "to" },
{ title: "BRAND", field: "carrier" },
{ title: "START DATE", field: "pickup_date" },
{ title: "ETD", field: "" },
{
title: "STATUS",
field: "current_status",
cellStyle: {
color: "green",
},
},
]}
```

React.js: Add action icons (edit, delete) in table using material-ui

I have an existing table wherein I used a library called react-bootstrap-table-next
It serves its purpose of showing data in a table in which the values are from a JSON response
However, I want to add an Action column containing edit and delete
I want to achieve this using material-ui icons
Any advice as to how should I start? Should I fully convert my table first into material-ui to achieve this?
OR I can just edit profiles state array and map it into a new array containing icons?
ProfileMaintenance.js
const [profiles, setProfiles] = useState([]); // populate table with saved profiles
const retrieveProfiles = useCallback(() => {
ProfileMaintenanceService.retrieveProfiles()
.then((response) => {
console.log(
"ProfileMaintenance - retrieveProfiles response.data >>> ",
response.data
);
setProfiles(response.data);
})
.catch((error) => {
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers); // send to logger
if (
error.response.data.error !== undefined &&
error.response.data.error != ""
) {
store.addNotification({
...notification,
type: "danger",
message: error.response.data.error,
dismiss: {
duration: 5000,
},
});
} else {
store.addNotification({
...notification,
type: "danger",
message:
"Server responded with a status code that falls out of the range of 2xx",
dismiss: {
duration: 5000,
},
});
}
} else if (error.request) {
// if API is down
console.log(error.request); // send to logger
store.addNotification({
...notification,
type: "danger",
message: "Request was made but no response was received",
dismiss: {
duration: 5000,
},
});
}
});
});
const columnsProfile = [
// {
// headerStyle: {
// backgroundColor: '#b3b3b3'
// },
// dataField: 'id', // for dev only
// text: 'ID',
// sort: true
// },
{
headerStyle: {
backgroundColor: "#b3b3b3",
},
dataField: "profileName",
text: "Name",
sort: true,
filter: textFilter(),
},
{
headerStyle: {
backgroundColor: "#b3b3b3",
},
dataField: "createdBy",
text: "Creator",
sort: true,
},
{
headerStyle: {
backgroundColor: "#b3b3b3",
},
dataField: "creationDate",
text: "Creation Date",
sort: true,
// filter: dateFilter()
},
{
headerStyle: {
backgroundColor: "#b3b3b3",
},
dataField: "lastModifier",
text: "Last Modifier",
sort: true,
},
{
headerStyle: {
backgroundColor: "#b3b3b3",
},
dataField: "lastModification",
text: "Last Modification",
sort: true,
},
{
headerStyle: {
backgroundColor: "#b3b3b3",
},
dataField: "action",
text: "Action",
},
];
const options = {
paginationSize: 4,
pageStartIndex: 1,
alwaysShowAllBtns: true,
hideSizePerPage: true,
firstPageText: "First",
prePageText: "Back",
nextPageText: "Next",
lastPageText: "Last",
nextPageTitle: "First page",
prePageTitle: "Pre page",
firstPageTitle: "Next page",
lastPageTitle: "Last page",
showTotal: true,
paginationTotalRenderer: customTotal,
sizePerPageList: [
{
text: "5",
value: 5,
},
{
text: "10",
value: 10,
},
{
text: "All",
value: profiles.length,
},
],
};
return (
<BootstrapTable
keyField="id"
hover
data={profiles}
columns={columnsProfile}
defaultSorted={defaultSorted}
filter={filterFactory()}
selectRow={selectRowClient}
noDataIndication="No record(s) found."
pagination={paginationFactory(options)}
/>
)
As you want material icon, I suggest to use material ui table. Please below example to edit or delete row from material ui table.
import React from 'react';
import MaterialTable from 'material-table';
export default function MaterialTableDemo() {
const [state, setState] = React.useState({
columns: [
{ title: 'Name', field: 'name' },
{ title: 'Surname', field: 'surname' },
{ title: 'Birth Year', field: 'birthYear', type: 'numeric' },
{
title: 'Birth Place',
field: 'birthCity',
lookup: { 34: 'İstanbul', 63: 'Şanlıurfa' },
},
],
data: [
{ name: 'Mehmet', surname: 'Baran', birthYear: 1987, birthCity: 63 },
{
name: 'Zerya Betül',
surname: 'Baran',
birthYear: 2017,
birthCity: 34,
},
],
});
return (
<MaterialTable
title="Editable Example"
columns={state.columns}
data={state.data}
editable={{
onRowAdd: (newData) =>
new Promise((resolve) => {
setTimeout(() => {
resolve();
setState((prevState) => {
const data = [...prevState.data];
data.push(newData);
return { ...prevState, data };
});
}, 600);
}),
onRowUpdate: (newData, oldData) =>
new Promise((resolve) => {
setTimeout(() => {
resolve();
if (oldData) {
setState((prevState) => {
const data = [...prevState.data];
data[data.indexOf(oldData)] = newData;
return { ...prevState, data };
});
}
}, 600);
}),
onRowDelete: (oldData) =>
new Promise((resolve) => {
setTimeout(() => {
resolve();
setState((prevState) => {
const data = [...prevState.data];
data.splice(data.indexOf(oldData), 1);
return { ...prevState, data };
});
}, 600);
}),
}}
/>
);
}

JTable jquery, Close Child button

I am using Jtable (Jquery based).
I have some trouble with the child table.
In the child table I added a new button in the toolbar.
With this new button in the toolbar, che close icon disappear, how can I fix it?
(if I remove the toolbar element the X of close button is correctly displayed).
$('#ListHeader').jtable({
title: 'ExpensesAccounts' ,
actions: {
listAction: function (postData, jtParams) {
return getListDataHeader();
}
},
fields: {
ID:{
key: true,
list:false
},
Details: {
title: '',
width: '5%',
sorting: false,
edit: false,
saveUserPreferences: false,
create: false,
display: function (headerData) {
//Create an image that will be used to open child table
var $img = $('<img src="../Images/viewDetails.png" width="20p" height="20p" title="View Details" />');
//Open child table when user clicks the image
$img.click(function () {
$('#ListHeader').jtable('openChildTable',
$img.closest('tr'),
{
title: headerData.record.Title + ' - Row' ,
saveUserPreferences: false,
paging: true,
pageSize: 3,
showCloseButton:true,
toolbar: {
items: [{
icon: '../scripts/jtable/themes/metro/add.png',
text: 'Add New Row',
click: function (headerID) {
window.location = "InsertRow.aspx";
}
}]
},
actions: {
listAction: function (postData, jtParams) {
return getListDataRow(headerData.record.ID, jtParams.jtStartIndex, jtParams.jtPageSize);
//return { "Result": "OK", "Records": [] };
},
deleteAction: function (postData) {
return deleteItem(postData, 'Expense Account Rows');
}
},
fields: {
HeaderID: {
type: 'hidden',
defaultValue: headerData.record.ID
},
ID: {
key: true,
create: false,
edit: false,
list: false
},
Title: {
title: 'Title',
width: '20%'
}
}
}, function (data) { //opened handler
data.childTable.jtable('load');
});
});
//Return image to show on the person row
return $img;
}
},
Title: {
title: 'Title'
},
Status: {
title: 'Status',
width: '8%'
}
}
});
$('#ListHeader').jtable('load');
Thanks,
Nk

Categories

Resources