Get Fetched Data to table data in material ui react - reactjs

I Have Fetched Some Data from a url via axios .I want to display those data to material ui table data in React. Here, 'patient' is the array where fetched data stored.
Code:
const [patient, setPatient] = React.useState([])
const [state, setState] = React.useState({
columns: [
{ title: 'Name', field: 'name' },
{ title: 'Gender', field: 'gender' },
{ title: 'Age', field: 'age', type : 'numeric' },
{ title: 'Birth Year', field: 'birthYear', type : 'numeric' },
{ title: 'Phone Number', field: 'phoneNumber', type : 'tele'
},
],
data: [
],
});
React.useEffect(()=>{
axios.get('http://127.0.0.1:8000/patient/AppModel/')
.then(res =>{
setPatient(res.data)
})
.catch(err=>{
console.log(err)
})
},[])
return (
<MaterialTable
title="Patient List"
columns={state.columns}
data={state.data}
/>
})}
But actually i don't how to get an array data to an array of objects.

Related

React Material-UI: Populating Rows in DataGrid returns undefined

In my React application, I want to fill the rows of a Material-UI Data Grid with backend data.
To achieve this, I make a GET request to the backend, which returns an AxiosResponse containing the data.
This AxiosResponse, I store in a variable named list, using useState().
Afterwards, I iterate over list to map the data to an Array of Objects, named testrows.
In the return method with DataGrid, I want to set property row to testrows.
However on rendering, it returns an error saying that testrow is undefined.
What am I doing wrong here?
import ...
export default function FruitList() {
const [list, setList] = useState<AxiosResponse>();
const columns: GridColDef[] = [
{
field: 'id',
headerName: 'Fruit ID',
type: 'number',
},
{
field: 'type',
headerName: 'Fruit Type',
type: 'string',
},
{
field: 'harvest',
headerName: 'Harvest Date',
type: "date",
},
{
field: 'entryDate',
headerName: 'Entry Date',
type: "date",
},
];
// Get list of fruits and store in variable "list"
useEffect(() => {
axios.get('http://localhost:3000/v1/fruit/'
.then(result => {
setList(result);
})
}, [])
let testrows = list?.data.map((element: { id: any, type: any, harvest: any, entryDate: any }) => {
return {
id: element.id,
type: element.type,
harvest: element.harvest,
entryDate: element.entryDate
}
}
);
// also tried useMemo:
const testrows = useMemo(() =>
list?.data.map((element: { id: any, type: any, harvest: any, entryDate: any }) => {
return {
id: element.id,
type: element.type,
harvest: element.harvest,
entryDate: element.entryDate
}
}),
[list?.data]
);
// console output: "test: undefined"
console.log("test: ", testrows);
return (
<div>
<div>
<DataGrid
rows={testrows}
columns={columns}
/>
</div>
</div>
);
}

Can't select checkbox table Ant Design

I'm currently learning ReactJs and using Ant Design as a UI library. I have some problems when I tried to use the Selection (Checkbox Table). At first, it's fine with some basic interaction, I can get the selectedRowKeys, the selectedRow data normally to interact with the database. But when I need the Table to check some rows according to the data, it got some problems. When I set the props selectedRowKeys with data, it selects the right checkbox I want but I can't uncheck or select another checkbox. It shows the error:
Uncaught TypeError: clone.push is not a function at arrAdd ...
Here's how I'm doing it:
import React, { useState } from 'react';
import { Table, Radio, Divider } from 'antd';
const columns = [
{
title: 'Name',
dataIndex: 'name',
render: (text) => <a>{text}</a>,
},
{
title: 'Age',
dataIndex: 'age',
},
{
title: 'Address',
dataIndex: 'address',
},
];
const data = [
{
key: '1',
name: 'John Brown',
age: 32,
address: 'New York No. 1 Lake Park',
},
{
key: '2',
name: 'Jim Green',
age: 42,
address: 'London No. 1 Lake Park',
},
{
key: '3',
name: 'Jack',
age: 20,
address: 'Somewhere else',
},
]; // rowSelection object indicates the need for row selection
const rowSelection = {
onChange: (selectedRowKeys, selectedRows) => {
console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
},
getCheckboxProps: (record) => ({
name: record.name,
}),
};
const Demo = () => {
const dataKeys = "1,2"; //after handling data from server, I got a string like this which I can pass to Table
return (
<div>
<Table
rowSelection={{
selectedRowKeys: dataKeys,
type: selectionType,
...rowSelection,
}}
columns={columns}
dataSource={data}
/>
</div>
);
};
ReactDOM.render(<Demo />, mountNode);

Retrieving value from row on click on button in grid React MUI

A project I am involved with has a react user grid component. The grid is populated by requesting data from the server. When I click on a button in a grid row, I need to get the value of the "_id" field of this particular row.
I only managed to get the _id of all rows, but I only need the value of the row where the button was clicked. In addition, the button click event occurs immediately on page load, not just on click.
const columns = [
{
field: '_id', headerName: 'id', type: 'number', flex: 0.9,
},
{
field: 'userName', headerName: 'Username', flex: 0.7,
},
{
field: 'email', headerName: 'email', flex: 0.7,
},
{
field: 'fullName', headerName: 'Full name', flex: 0.7,
},
{
field: 'status', headerName: 'Status', flex: 0.7,
},
{
field: 'actions',
type: 'actions',
headerName: 'Actions',
flex: 0.2,
getActions: (params) => [
<IconButton onClick={console.log(params.row._id)}>
<EditIcon />
</IconButton>,
],
},
];
function generateRows(users) {
return users.map((user) => (({
_id, userName, email, fullName, status,
}) => ({
_id, userName, email, fullName, status,
}))(user));
}
export default function UserControlTable() {
const [data, setData] = useState({
users: [],
});
useEffect(() => {
const fetchUsers = async () => {
const users = await axios.get(process.env.REACT_APP_API_URL + USER_LIST);
setData({ users: generateRows(users.data)});
};
fetchUsers();
}, []);
return (
<Container>
<DataGrid
getRowId={(row) => row._id}
rows={data.users}
columns={columns}
checkboxSelection
column
/>
</Container>
);
}
Like my comment above try:
onClick={() => console.log(params.row._id)}
instead of
onClick={console.log(params.row._id)}
You have to return an arrow function inside the onClick event handler.

ReactJs MaterialUi onRowUpdate field validation

I have a MaterialTable and I want to validate the fields when editing a line.
For example the following code:
https://codesandbox.io/s/broken-snow-i4jbi?fontsize=14&hidenavigation=1&theme=dark
I have the function setNameError
const [nameError, setNameError] = useState({
error: false,
label: '',
helperText: '',
});
Then the onRowUpdate:
onRowUpdate: (newData, oldData) =>
new Promise((resolve, reject) => {
setTimeout(() => {
if(newData.name === '') {
setNameError({
error: true,
label: 'required',
helperText: 'Required helper text'
});
reject();
return;
}
resolve();
...
}, 600);
})
I want to validate if the field name is empty, if it is empty I want to have this aspect:
validation in the field after click Save button
I can't show the error label, it looks like the setNameError inside the Promise is not working and I don't understand how can I do this.
Found the problem
I was storing the columns in state
const [state, setState] = React.useState({
columns: [
{ title: 'Name', field: 'name',
editComponent: props => (
<TextField
type="text"
required={true}
error = {nameError.error}
label = {nameError.label}
helperText = {nameError.helperText}
value={props.value ? props.value : '' }
onChange={e => props.onChange(e.target.value)}
/>
)
},
{ 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,
},
],
});
And then passing the state.columns to the MaterialTable component:
<MaterialTable
title="Editable Example"
columns={state.columns}
data={state.data}
...
The solution was to put the columns definition in the MaterialTable component:
return (
<MaterialTable
title="Editable Example"
columns= {[
{ title: 'Name', field: 'name',
editComponent: props => (
<TextField
type="text"
required={true}
error = {nameError.error}
label = {nameError.label}
helperText = {nameError.helperText}
value={props.value ? props.value : '' }
onChange={e => props.onChange(e.target.value)}
/>
)
},
{ title: 'Surname', field: 'surname' },
{ title: 'Birth Year', field: 'birthYear', type: 'numeric' },
{
title: 'Birth Place',
field: 'birthCity',
lookup: { 34: 'İstanbul', 63: 'Şanlıurfa' },
},
]}
data={state.data}
...

How to do onclick on particular table row in MaterialTable

I have two issues in MaterialTable
* I am using MaterialTable in reactjs , i want to do onClick on particular row . I am passing JSON data in table. How can i implement this?
columns: [
{ title: 'Username', field: 'username' },
{ title: 'Team Membership', field: 'teammembership' },
],
<MaterialTable
title = "Team Members"
columns={this.state.columns}
data={this.state.rowData}
/>
teammembership should be clickable
*How to add a button in particular row, rather than action? I am already using action in first row , i want to add one button not along with action, but in 3rd row.
columns: [
{ title: 'User Name', field: 'username' },
{ title: 'Role',
field: 'roles',
lookup: { 34: 'Primary', 63: 'Secondary' ,53 : 'Escallation', 54:'Override ' },
},
{ title: 'Start Date', field: 'Startdate', type: 'datetime' },
{ title: 'End Date', field: 'enddate', type: 'datetime' },
{title : 'Repeat', field:'repeat'},
],
data: [
{ username: 'Mehmet', roles: '34', Startdate: 1987, enddate: 2018,repeat:'repeat' },
{
username: 'Zerya Betül',
roles: '63',
Startdate: 2017,
enddate: 2019,
repeat:'repeat'
},
],
<MaterialTable
title = ""
columns={this.state.columns}
data={ this.state.data}
editable={{
onRowAdd: newData =>
new Promise(resolve => {
setTimeout(() => {
resolve();
const data = [...this.state.data];
data.push(newData);
setState({ ...this.state, data });
}, 600);
}),
onRowUpdate: (newData, oldData) =>
new Promise(resolve => {
setTimeout(() => {
resolve();
const data = [...this.state.data];
data[data.indexOf(oldData)] = newData;
setState({ ...this.state, data });
}, 600);
}),
onRowDelete: oldData =>
new Promise(resolve => {
setTimeout(() => {
resolve();
const data = [...this.state.data];
data.splice(data.indexOf(oldData), 1);
setState({ ...this.state, data });
}, 600);
}),
}}
/>
in the place of repeat i want to place a button
Any help would be appreciated. Thank you.
The component has an onRowClick prop which can be used to have things happen onClick of a given row. Please see the documentation here and look specifically at the section "Detail Panel With RowClick Example".

Resources