React-Table not rendering data - javascript

I am trying to render some data in a react-table component however the data doesn't load. I have tested out with dummy data of the exact same format and it works fine. However when I make an API call and get data of the same format and push it to the list of data i'm passing to the react-table the table does not render it. Please help me identify the issue. Cheers
Setting up the columns:
columns: [
{
Header: "Employee ID",
accessor: "EmployeeID"
},
{
Header: "First Name",
accessor: "FirstName"
},
{
Header: "Last Name",
accessor: "LastName"
},
{
Header: "Date of Birth",
accessor: "DateOfBirth",
},
{
Header: "Status",
accessor: "Status",
},
{
Header: "Gender",
accessor: "Gender",
},
{
Header: "UpdatedDateUTC",
accessor: "UpdatedDateUTC",
}
]
What the data looks like:
{"EmployeeID":"63c571b3-bff0-4ce1-94f7-255c235580fa","FirstName":"Clive","LastName":"Thomas","Status":"ACTIVE","DateOfBirth":"/Date(697248000000+0000)/","Gender":"M","UpdatedDateUTC":"/Date(1533706298000+0000)/"}
My API call and how I'm saving the data item to state. (I console logged the value of the data I'm getting and it is in the correct format)
fetch('http://localhost:3100/employees')
.then((resp) => {
return resp.json()
})
.then((data) => {
let temp = this.state.posts;
temp.push(data.Employees[1])
this.setState({posts: temp})
console.log(this.state.posts)
})
.catch((error) => {
console.log(error, "catch the hoop")
})
The state and the 'posts' list storing the posts in state at bottom (with dummy data):
state = {
title: "Choose an Endpoint",
activeOrg: "Orginisation",
isExpanded: false,
activeLink: 0,
authLink:'',
response: '',
post: '',
responseToPost: '',
show: false,
modalContent:"",
token:'',
verifier:'',
org:'',
orginisations: [
{ id: 1, name: "ANU"},
{ id: 2, name: "Bar"},
{ id: 3, name: "FANG"},
{ id: 4, name: "Atlassian"}
],
list: [
{ id: 1, name: "Employees" },
{ id: 2, name: "Leave Applications" },
{ id: 3, name: "Pay Items" },
{ id: 4, name: "Payroll Calendars" },
{ id: 5, name: "Pay Runs" },
{ id: 6, name: "Pay Slips" },
{ id: 7, name: "Settings" },
{ id: 8, name: "Superfund Products" },
{ id: 9, name: "Timesheets" }
],
columns: [
{
Header: "Employee ID",
accessor: "EmployeeID"
},
{
Header: "First Name",
accessor: "FirstName"
},
{
Header: "Last Name",
accessor: "LastName"
},
{
Header: "Date of Birth",
accessor: "DateOfBirth",
},
{
Header: "Status",
accessor: "Status",
},
{
Header: "Gender",
accessor: "Gender",
},
{
Header: "UpdatedDateUTC",
accessor: "UpdatedDateUTC",
}
],
posts: [
{"EmployeeID":"63c571b3-bff0-4ce1-94f7-255c235580fa","FirstName":"Clive","LastName":"Thomas","Status":"ACTIVE","DateOfBirth":"/Date(697248000000+0000)/","Gender":"M","UpdatedDateUTC":"/Date(1533706298000+0000)/"}
]
}
Render function:
render() {
let myClass=""
let EndpointList = (
<div>
{this.state.list.map((i) => {
i.id === this.state.activeLink ? myClass="endpoint activeLink" : myClass="endpoint"
return <Endpoint
key={i.id}
name={i.name}
myClass={myClass}
clicked={(event) => this.handleClickEndpoint(i, i.id)}/>
})}
</div>
);
let orgContainer = ""
this.state.isExpanded ? orgContainer="orgItem expanded" : orgContainer="orgItem notExpanded"
let OrgList = (
<div className={orgContainer}>
{this.state.orginisations.map((o) => {
return <Orginisation
key={o.id}
name={o.name}
clicked={(event) => this.handleClickOrg(o,o.id)}
></Orginisation>
})}
</div>
);
var activeContent=<ReactTable columns={this.state.columns} data={this.state.posts} noDataText={"Loading..."}></ReactTable>
// const columns = Object.keys(this.state.data[0]).map((key, id)=>{
// console.log(key)
// return {
// Header: key,
// accessor: key,
// }
// })
return (
<Router>
<Route path='/' exact render={
() => {
return (
<div className='authenticateContainer'>
<a href={this.state.authLink} className='fill-div'>Click to Auntheticate</a>
</div>
)
}
}/>
<Route path='/home' render={
() => {
return (
<div>
<div className='sideBar'>
<div className='logoHolder'>
<img className='logo' alt='Logo' src={'./Assets/logo.png'}></img>
</div>
{EndpointList}
{OrgList}
<div style={{}} className="org button" onClick={this.expandOrg}>
<img className="orgLogo" alt='Logo' src={'./Assets/orgLogo.png'}></img>
{this.state.activeOrg}
</div>
</div>
<div className="container" id={this.state.title}>
{/* <button onClick={() => { this.setCredentials() }}>CLICK ME</button> */}
<div className="contentContainer">
<div className="head">
{this.state.title}
</div>
{activeContent}
</div>
</div>
</div>
)
}
} />
</Router>
);
}
}
Instantiating the react-table (also in render function above):
var activeContent=<ReactTable columns={this.state.columns} data={this.state.posts} noDataText={"Loading..."}></ReactTable>
I have also printed the dummy data that is successfully being inserted into the list as well as the API data which is not. As you can see they are clearly identical:

Not sure if this will resolve your issue, but IMO you should refactor this to be
fetch('http://localhost:3100/employees')
.then((resp) => {
return resp.json()
})
.then((data) => {
let temp = [...this.state.posts]
temp.push(data.Employees[1])
this.setState({
posts: temp,
data: data
})
console.log(this.state.posts) //this will not have the newest values yet, setState is async
})
.catch((error) => {
console.log(error, "catch the hoop")
})
It's not good practice to perform manipulations on react state

Why are you pushing Employees[1]? That would be the second record.

Related

EditableProTable Edit is Not working in ant design pro

I created table with ant design ProTable Component and its Edit function is not working. It showing error like this. ("Cannot read properties of undefined (reading 'toString')"). I tried many ways to solve this problem and cannot found a solution yet.
I want get table data from CSV file upload. That function is already working and data retrieved to the table.
const columns = [
{
title: 'First Name',
valueType: 'string',
typeof:'string',
dataIndex: 'fName',
formItemProps: () => {
return {
rules: [{ required: true, message: '' }],
};
},
},
{
title: 'Last Name',
valueType: 'string',
typeof:'string',
dataIndex: 'lName',
formItemProps: () => {
return {
rules: [{ required: true, message: '' }],
};
},
},
{
title: 'Email',
valueType: 'string',
typeof:'string',
dataIndex: 'email',
formItemProps: () => {
return {
rules: [{ required: true, message: '' }],
};
},
},
{
title: 'Position',
valueType: 'string',
typeof:'string',
dataIndex: 'position',
formItemProps: () => {
return {
rules: [{ required: true, message: '' }],
};
},
},
{
title: 'Actions',
valueType: 'option',
width: 200,
render: (text, record, _, action) => [
<a
key="delete"
onClick={() => {
setData(data.filter((item) => item.id !== record.id));
}}
>
Delete
</a>,
<a
key="editable"
onClick={() => {
var _a;
(_a = action === null || action === void 0 ? void 0 : action.startEditable) === null ||
_a === void 0
? void 0
: _a.call(action, record.id);
}}
>
Edit
</a>,
],
},
];
EditableProTable
rowKey="id"
actionRef={actionRef}
headerTitle=""
maxLength={5}
recordCreatorProps={false}
columns={columns}
request={async () => ({
data: data,
total: 3,
success: true,
})}
value={csvArray}
onChange={setCsvArray}
editable={{
type: 'multiple',
editableKeys,
onSave: async (rowKey, data, row) => {
await waitTime(2000);
},
onChange: setEditableRowKeys,
actionRender: (row, config, defaultDom) => [
defaultDom.save,
defaultDom.delete || defaultDom.cancel,
],
}}
/>[![enter image description here][1]][1]
The editableKeys array contains rows that are in the editing state
const [editableKeys, setEditableRowKeys] = useState(() => csvArray.map((item) => item.index)); // or .map((item=) => item.key));

How do I get hover effect on rows with material-table react?

I have used material-table with react to render my data. I want to show the hover effect and cursor pointer effect when I hover on rows. But I couldn't find this even in the documentation.
IN SHORT- I want to highlight some colors on a row when the cursor hovers to that row.
Note: I also found a similar question and answer here, but they used another state just to hover which downgrades the performance if I increase the data like thousands rows. Hence it's bad practice so here I am asking for alternate solutions for the same.
Here is my codesandbox link
Below I also pasted my code.
App.js
import React, { useState } from 'react';
import './App.css';
import MaterialTable from 'material-table'
const empList = [
{ id: 1, name: "Neeraj", email: 'neeraj#gmail.com', phone: 9876543210, city: "Bangalore" },
{ id: 2, name: "Raj", email: 'raj#gmail.com', phone: 9812345678, city: "Chennai" },
{ id: 3, name: "David", email: 'david342#gmail.com', phone: 7896536289, city: "Jaipur" },
{ id: 4, name: "Vikas", email: 'vikas75#gmail.com', phone: 9087654321, city: "Hyderabad" },
]
function App() {
const [data, setData] = useState(empList)
const columns = [
{ title: "ID", field: "id", editable: false },
{ title: "Name", field: "name" },
{ title: "Email", field: "email" },
{ title: "Phone Number", field: 'phone', },
{ title: "City", field: "city", }
]
return (
<div className="App">
<h1 align="center">React-App</h1>
<h4 align='center'>Material Table with CRUD operation</h4>
<MaterialTable
title="Employee Data"
data={data}
columns={columns}
editable={{
onRowAdd: (newRow) => new Promise((resolve, reject) => {
const updatedRows = [...data, { id: Math.floor(Math.random() * 100), ...newRow }]
setTimeout(() => {
setData(updatedRows)
resolve()
}, 2000)
}),
onRowDelete: selectedRow => new Promise((resolve, reject) => {
const index = selectedRow.tableData.id;
const updatedRows = [...data]
updatedRows.splice(index, 1)
setTimeout(() => {
setData(updatedRows)
resolve()
}, 2000)
}),
onRowUpdate:(updatedRow,oldRow)=>new Promise((resolve,reject)=>{
const index=oldRow.tableData.id;
const updatedRows=[...data]
updatedRows[index]=updatedRow
setTimeout(() => {
setData(updatedRows)
resolve()
}, 2000)
})
}}
options={{
actionsColumnIndex: -1, addRowPosition: "first"
}}
/>
</div>
);
}
export default App;
add in your inside of your CSS
tbody tr:hover {
background-color: blue;
color: white;
cursor: pointer;
}

react-sortablejs - Setting the 'onChange' method on an object with nested arrays

I'm using the react-sortablejs library.
When trying to move cards within the list. I get the error:
Cannot read property 'map' of undefined
I have a dense structure and it gets lost here. How to handle onChange so that I can see in the console that the order of the notes within the list has changed.
Demo here
import Sortable from 'react-sortablejs';
// Functional Component
const SortableList = ({ items, onChange }) => {
return (
<div>
<Sortable
tag="ul"
onChange={(order, sortable, evt) => {
console.log(order)
onChange(order);
}}
>
{items.listItems.map(val => {
return <li key={uniqueId()} data-id={val}>List Item: {val.title}</li>})
}
</Sortable>
</div>
);
};
class App extends React.Component {
state = {
item: {
id: "abc123",
name: "AAA",
lists: [
{
id: "def456",
list_id: "654wer",
title: 'List1',
desc: "description",
listItems: [
{
id: "ghj678",
title: "ListItems1",
listItemsId: "88abf1"
},
{
id: "poi098",
title: "ListItems2",
listItemsId: "2a49f25"
},
{
id: "1oiwewedf098",
title: "ListItems3",
listItemsId: "1a49f25dsd8"
}
]
},
{
id: "1ef456",
list_id: "654wer",
title: 'List 2',
desc: "description",
listItems: [
{
id: "1hj678",
title: "ListItems4",
listItemsId: "18abf1"
},
{
id: "1oi098",
title: "ListItems5",
listItemsId: "1a49f25"
},
{
id: "1oiwewe098",
title: "ListItems6",
listItemsId: "1a49f25dsd"
}
]
},
{
id: "2ef456",
title: 'List 3',
list_id: "254wer",
desc: "description",
listItems: [
{
id: "2hj678",
title: "ListItems7",
listItemsId: "28abf1"
},
{
id: "2oi098",
title: "ListItems8",
listItemsId: "234a49f25"
},
{
id: "df098",
title: "ListItems9",
listItemsId: "1asd8"
}
]
}
]
}
};
render() {
const c = this.state.item['lists'].map(item => { return item.listItems});
return (
this.state.item['lists'].map(item => {
return (<div>
{item.title}
<SortableList
key={uniqueId()}
items={item}
onChange={(item) => {
console.log(item)
this.setState({item});
}}
>
</SortableList>
</div>)
})
)
}
};
Thanks in advance.
You have to update few changes in your code.
Update the SortableList function as below.
First pass data-id={val.id} in li and after that in onChange method you will receive the order with id. So based on that we are sorting the records.
const SortableList = ({ items, onChange }) => {
return (
<div>
<Sortable
tag="ul"
onChange={(order, sortable, evt) => {
items.listItems.sort(function(a, b){
return order.indexOf(a.id) - order.indexOf(b.id);
});
onChange(items);
}}
>
{items.listItems.map(val => {
return <li key={uniqueId()} data-id={val.id}>List Item: {val.title}</li>})
}
</Sortable>
</div>
);
};
Update the onChange event of App component.
onChange={(item) => {
let itemObj = {...this.state.item};
itemObj.lists.map(x=>{
if(x.id === item.id) x = item;
});
this.setState({itemObj});
}}
That's it!
Here is the working demo for you
https://stackblitz.com/edit/react-sortablejs-blzxwd
When remove the onChange event in the Sortable list, Its works.
const SortableList = ({ items, onChange }) => {
return (
<div>
<Sortable
tag="ul"
>
{items.listItems.map(val => {
return <li key={uniqueId()} data-id={val}>List Item: {val.title}</li>})
}
</Sortable>
</div>
);
};

React table not displaying data

so im using react-table library to display a tree grid table with mocked data but it isn't appearing like it should and it shows that there's one item on the table.
import React, { Component } from 'react';
import ReactTable from "react-table";
import 'react-table/react-table.css'
export default class TestTable extends Component {
state = {
data: [{
actionNo: "1",
action: "--",
productService: "Mobile Contract",
qty: 1,
startDate: Date.now(),
endDate: Date.now(),
account: 11111111,
mobileNo: 9111111,
amount: "--",
status: "Error"
}]
}
render() {
const { data } = this.state;
console.log(data);
const columns = [{
Header: 'Action No.',
accessor: 'actionNo'
}, {
Header: 'Action',
accessor: 'action',
}, {
acessor: 'productService',
Header: 'Product/Service',
}, {
acessor: 'qty',
Header: 'Qty.',
}, {
acessor: 'startDate',
Header: 'Start Date',
}, {
acessor: 'endDate',
Header: 'End Date',
}, {
acessor: 'account',
Header: 'Account',
}, {
acessor: 'mobileNo',
Header: 'Mobile No.',
}, {
acessor: 'amount',
Header: 'Amount.',
}, {
acessor: 'status',
Header: 'Status',
}]
return (
<ReactTable
data={data}
columns={columns}
pivotBy={["actionNo"]}
defaultPageSize={10}
showPagination={false}
resizable={false}
noDataText="No Data!"
className="-striped -highlight"
/>
);
}
}
This is the result of the snippet above
:
Soon i'll be using real data from a database but i need to test this out before messing around with micro service integration.
It's a typo. Please try using 'accessor' instead of 'acessor'.

How can I change this url to a link in that code when using ReactTable?

Here is React code:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import ReactTable from 'react-table';
import _ from 'lodash';
import './style.css';
class GithubDataTable extends Component {
render() {
const { showData, savedData } = this.props;
let data = null;
if (showData === 'last') {
data = _.last(savedData);
} else {
data = savedData[showData];
}
console.log(data);
return (
<div>
{data && (
<ReactTable
data={data.items}
columns={[
{
Header: 'Data from GitHub',
columns: [
{
Header: 'Id',
id: 'id',
accessor: d => d.id,
},
{
Header: 'Repo Title',
id: 'repoTitle',
accessor: d => d.name,
},
{
Header: 'Owner',
id: 'owner',
accessor: d => d.owner.login,
},
{
Header: 'Link',
id: 'link',
accessor: d => d.html_url, // example data string "https://github.com/Michaelcj10/ReactJS-GitHub-User-Finder-App"
},
{
Header: 'Created at',
id: 'createdAt',
accessor: d => d.created_at.slice(0, 10),
},
{
Header: 'Updated at',
id: 'updatedAt',
accessor: d => d.updated_at.slice(0, 10),
},
{
Header: 'Stars',
id: 'stars',
accessor: d => d.stargazers_count,
},
{
Header: 'Forks',
id: 'forks',
accessor: d => d.forks_count,
},
],
},
]}
defaultPageSize={10}
pageSizeOptions={[5, 10, 15, 20]}
className="-striped -highlight"
/>
)}
</div>
);
}
}
function mapStateToProps(state) {
return {
savedData: state.savedData,
showData: state.showData,
};
}
export default connect(mapStateToProps, null)(GithubDataTable);
And I have problem with that particular element:
{
Header: 'Link',
id: 'link',
accessor: d => d.html_url, // https://github.com/Michaelcj10/ReactJS-GitHub-User-Finder-App
},
Data is shown as text, but how can I add html in that particular situation to this JSX to obtain a link
Not enought text hack:
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters...
Looks like you might be able to use the Cell property to display custom markup:
{
Header: 'Link',
id: 'link',
accessor: d => d.html_url, // https://github.com/Michaelcj10/ReactJS-GitHub-User-Finder-App
Cell: props => <a href={props.value}>{props.value}</a>
},

Categories