//CODE
import React, { Component } from "react";
import ReactDOM from "react-dom";
import ColumnResizer from "column-resizer";
import "./table.css"
import axios from "axios";
class ReactTable extends Component {
constructor(props) {
super(props);
this.tableSelector = "#somethingUnique";
this.state = {
Data: [],
Data1: [],
error: '',
image: [],
}
}
//Fetching Api through LocalHost8080
getFetchData() {
axios.get(' /AmpRestAPI/webresources/getPCRList/all',
{
headers: {
'Access-Control-Allow-Origin': '*',
},
auth: {
username: 'admin',
password: 'password'
}
})
.then(async (response) => {
console.log(response.data);
this.setState({ Data: response.data });
}).catch(error => {
this.setState({ error: 'unable to fetch URL' });
console.log(error.response);
});
}
componentDidMount() {
if (this.props.resizable) {
this.enableResize();
this.getFetchData();
}
}
componentWillUnmount() {
if (this.props.resizable) {
this.disableResize();
}
}
componentDidUpdate() {
if (this.props.resizable) {
this.enableResize();
}
}
UNSAFE_componentWillUpdate() {
if (this.props.resizable) {
this.disableResize();
}
}
enableResize() {
const options = this.props.resizerOptions;
if (!this.resizer) {
this.resizer = new ColumnResizer(
ReactDOM.findDOMNode(this).querySelector(`${this.tableSelector}`),
options
);
} else {
this.resizer.reset(options);
}
}
disableResize() {
if (this.resizer) {
this.resizer.reset({ disable: true });
}
}
render() {
const { Data, error } = this.state
return (
<div>
<div className="container-fluid pt-3">
<table id="somethingUnique" cellSpacing="0" className="border-primary">
<thead>
<tr>
<th>Thumbnail</th>
<th >ChannelName
</th>
<th>Duration
</th>
<th>
thEndTime
</th>
<th>LoadedClip</th>
<th>Start Time</th>
<th>CurrentTimeStamp
</th>
</tr>
</thead>
<tbody>
{Data.length ?
Data.map((val, index) => {
//flitter
const filterValue = this.props.filterValue;
const emplogin = val.ChannelName.toLowerCase();
// const emptype = emp.type;
if (((!filterValue) || (emplogin.indexOf(filterValue) !== -1))) {
return (
<tr key={index}>
<td>
{this.state.image ? <img src={`data:image/jpeg;base64,${val.Thumbnail}`} alt="Clip Thumbnail" width="100%" height="100%" /> : ''}
</td>
<td>
{val.ChannelName}
</td>
<td>{val.Duration} </td>
<td> {val.EndTime}
</td>
<td>
{val.LoadedClip}
</td>
<td>
{val.StartTime}
</td>
<td>
{val.CurrentTimeStamp}
</td>
</tr>
)
}
return true;
}
) : null
}
</tbody>
</table>
{
error ? <div className="text-center pt-4"><h5>{error}</h5></div> : null
}
</div >
</div >
);
}
}
export default ReactTable;
I want to fetch both PCR1 and PCR2 without using a spread operator. If the admin added PCR3 then that part also be displayed in a Web browser. See in the given name(Console Image). If the admin Added more PCR then how to fetch that data .please help
I did this.setState({ Data: response.data }); to show PCR1 AND PCR2 in Table but not able to display.
**without using Spread Operator this.setState({Data: [...response.data.PCR1, ...response.data.PCR2]});** thanks in advance
[1]: https://i.stack.imgur.com/VkZDw.png
I did this.setState({ Data: response.data }); to show PCR1 AND PCR2 in Table but not able to display.
without using Spread Operator this.setState({Data: [...response.data.PCR1, ...response.data.PCR2]}); thanks in advance I did this.setState({ Data: response.data }); to show PCR1 AND PCR2 in Table but not able to display.
without using Spread Operator this.setState({Data: [...response.data.PCR1, ...response.data.PCR2]}); thanks in advance
Try this:
this.setState({Data: [...Object.values(response.data).flat()]});
Related
I am trying to use reactstrap's Collapse to collapse two alternating sections.
import React, { Component, Fragment, Suspense } from "react";
import ReactDOM from 'react-dom';
import { PDFViewer } from '#react-pdf/renderer'
import NewWindow from 'react-new-window'
import Config from 'config';
import { Button, Collapse } from 'reactstrap';
import { formatter } from '../common.js'
import { format } from 'date-fns';
import Pagination from '../Pagination';
import "./Order.css";
import Modal from 'react-modal';
import PaymentModal from './paymentModal.js';
import Invoice from './Reports/Invoice';
Modal.setAppElement('#root');
let PageSize = 25;
class Portal extends React.Component {
constructor() {
super();
this.state = {
name: 'React',
apiData: [],
currentPage: 1,
currentTableData: [],
orderList: [],
isOpen: false,
pdfView: null,
viewInvoices: true,
viewOrders: false
};
}
showInvoices() {
console.log("Show Invoices Clicked")
this.setState({ viewInvoices: true });
this.setState({ viewOrders: false });
}
showOrders() {
console.log("Show Orders Clicked")
this.setState({ viewInvoices: false });
this.setState({ viewOrders: true });
}
async componentDidMount() {
console.log('app mounted');
const tokenString = sessionStorage.getItem("token");
const token = JSON.parse(tokenString);
let headers = new Headers({
"Accept": "application/json",
"Content-Type": "application/json",
'Authorization': 'Bearer ' + token.token
});
const response = await fetch(Config.apiUrl + `/api/Orders/GetAllInvoices`, {
method: "GET",
headers: headers
});
const json = await response.json();
console.log(json);
this.setState({ orderList: json });
}
componentDidUpdate(_, prevState) {
console.log('Component Updated');
if (prevState.currentPage !== this.state.currentPage || prevState.orderList !== this.state.orderList) {
const firstPageIndex = (this.state.currentPage - 1) * PageSize;
const lastPageIndex = firstPageIndex + PageSize;
this.setState({ currentTableData: this.state.orderList.slice(firstPageIndex, lastPageIndex) });
}
}
render() {
const orders = this.state.orderList;
const currentTableData = this.state.currentTableData;
const { isOpen } = this.state;
let onRequestClose = () => {
this.setState({ isOpen: false });
}
let handleClick = () => {
console.log("Clicked")
this.setState({ isOpen: true });
}
function handleInvoiceClick(e, invoice) {
e.preventDefault();
console.log(`invoice: ${JSON.stringify(invoice)}`)
if (this.state.pdfView === null) {
const headerString = sessionStorage.getItem("header");
const header = JSON.parse(headerString);
const buff = new Buffer(header.logoImage, 'base64');
let pdf = (
<PDFViewer width="1000" height="600" className="portal">
<Invoice invoice={invoice} buff={buff} />
</PDFViewer>
);
this.setState({ pdfView: pdf });
} else {
this.setState({ pdfView: null });
}
}
handleInvoiceClick = handleInvoiceClick.bind(this);
return (
<div id="bootstrap-overrides">
<h2>Portal</h2>
<div className="row">
<div className="block col-1">
<p><button onClick={this.showInvoices.bind(this)}>Invoices</button></p>
<p><button onClick={this.showOrders.bind(this)}>Orders</button></p>
</div>
<div className="block col-2">
<br />
{this.state.pdfView}
<Collapse isOpen={this.state.showInvoices}>
<h3>Open Invoices</h3>
<h4>A list of completed orders purchased under this account.</h4>
<table className="table table-striped table-bordered">
<thead>
<tr>
<th className="number">Invoice Number</th>
<th className="date">Invoice Date</th>
<th className="date">Due Date</th>
<th className="amount">Total</th>
<th className="customer">Ship To</th>
<th className="date">Actual Ship Date</th>
<th className="button"></th>
</tr>
</thead>
<tbody>
{currentTableData && currentTableData.map(order =>
<>
<tr key={order.sopnumbe}>
<td><a href="#" onClick={(e) => handleInvoiceClick(e, order)}>{order.sopnumbe}</a></td>
<td>{format(Date.parse(order.invodate), 'MM/dd/yyyy')}</td>
<td>{format(Date.parse(order.duedate), 'MM/dd/yyyy')}</td>
<td>{formatter.format(order.docamnt)}</td>
<td>{order.custname}</td>
<td>{format(Date.parse(order.actlship), 'MM/dd/yyyy')}</td>
<td><Button className="BtnPay" onClick={handleClick}>Pay</Button></td>
</tr>
{isOpen ? <PaymentModal invoice={order} onRequestClose={onRequestClose} /> : null}
</>
)}
</tbody>
</table>
<Pagination
className="pagination-bar"
currentPage={this.state.currentPage}
totalCount={orders.length}
pageSize={PageSize}
onPageChange={page => this.setState({ currentPage: page })}
/>
</Collapse>
<Collapse isOpen={this.state.showOrders}>
<h3>Open Orders</h3>
<h4>A list of completed orders purchased under this account.</h4>
</Collapse>
</div>
</div>
</div>
);
}
}
export default Portal;
The isOpen doesn't seem to be reading my state. The Portal loads with both sections collapsed. My two buttons run (I get a console log entry for both) but don't effect the display. I would think the initial Invoice should be open as well. Why does my reactstrap Collapse element not reflect my initial or changed state? Do I need to add anything to componentDidUpdate? Any tips or advice will be appreciated.
reactstrap = reactstrap#9.0.1
I think you are using the wrong variables
<Collapse isOpen={this.state.showInvoices}>
<Collapse isOpen={this.state.showOrders}>
should be
<Collapse isOpen={this.state.viewInvoices}>
<Collapse isOpen={this.state.viewOrders}>
The show.. ones are the functions. The isOpen expects a boolean value
I have this on the front end (react) right now.
import '../styles/TourPage.css';
import React, { Component } from 'react';
import axios from 'axios'
class TourPage extends Component {
constructor(props) {
super(props);
this.state = {
myData: []
}
}
componentDidMount() {
axios.get('/getResults')
.then( res => {
console.log("Res is: ", res.data)
this.setState({
myData: res.data
});
})
console.log("res.data", this.state.myData)
}
render() {
console.log("res.data", this.state.myData)
return (
<table id="customers">
<tr>
<th>siteLocation</th>
<th>Services</th>
<th>cnum</th>
</tr>
{this.state.myData.length > 0? this.state.myData.map((data, index) => (
<tr>
{/* <tr key={index}> */}
<td>{data.location}</td>
<td>{data.Services}</td>
<td>{data.cnum}</td>
<button onClick={this.click} disabled={this.state.isLoading}> Delete </button>
{/* {this.state.data} */}
{/* </tr> */}
</tr>
))
: "No Data Found"}
</table>
);
}
}
export default TourPage;
What I want to do, is on a button click, set data._id in the state, and then call Axios to post it to the Node.JS backend server, so I can update the database. Basically to delete the document. as you can see below, I tried with <a href> but that seems to be an HTML-specific thing. I also tried with the button, but I cannot figure it out. How can I do this?
I have refactored most of your code. You can pass id using an anonymous arrow function.
Do modify this to suit your needs.
import { render } from "react-dom";
import React, { Component } from "react";
import axios from "axios";
import "../styles/TourPage.css";
class TourPage extends Component {
constructor(props) {
super(props);
this.state = {
myData: [],
isLoading: true
};
}
componentDidMount() {
axios
.get("/getResults")
.then((res) => {
this.setState({
myData: res.data
});
})
.catch((error) => {
// Handle the errors here
console.log(error);
})
.finally(() => {
this.setState({
isLoading: false
});
});
}
deleteById = (id) => {
// You'll get the id here
// Delete by id code goes here
};
render() {
// You can handle the loader part here with isLoading flag. In this case No data found will be shown initially and then the actual data
let { myData, isLoading } = this.state;
return (
<table id="customers">
<tr>
<th>siteLocation</th>
<th>Services</th>
<th>cnum</th>
</tr>
{myData.length > 0
? myData.map(({ location, Services, cnum, _id }, index) => (
<tr key={index}>
<td>{location}</td>
<td>{Services}</td>
<td>{cnum}</td>
<button
onClick={() => this.deleteById(_id)}
disabled={isLoading}
>
Delete
</button>
</tr>
))
: "No Data Found"}
</table>
);
}
}
export default TourPage;
Can you try this ?
render() {
deleteDoc = (id) => {
await fetch('service_url', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: id} )
.then(async response => {
await response.json().then(data => {
console.log(data);
});
})
.catch(err => {
console.log(err)
})
}
return (
<table id="customers">
<tr>
<th>siteLocation</th>
<th>Services</th>
<th>cnum</th>
</tr>
{this.state.myData.length > 0 ? this.state.myData.map((data, index) => (
<tr>
<td>{data.location}</td>
<td>{data.Services}</td>
<td>{data.cnum}</td>
<button onClick={this.deleteDoc(data._id)} disabled={this.state.isLoading}> Delete </button>
</tr>
))
: "No Data Found"}
</table>
);
}
I am failing to delete the clients from the API, i expected to click on Onclick button and the data should be deleted from the database:
Using the onclick button, the data should be deleted:
import React, { useRef } from 'react'
import ReactToPrint from 'react-to-print'
import { Table, Button } from 'react-bootstrap'
const Hello = () => {
alert('Name, Description, Start Date, End Date, Validity, Status')
}
class clientview extends React.Component {
constructor (props) {
super(props)
this.state = {
error: null,
clients: []
}
this.deleteTask = this.deleteTask.bind(this)
}
componentDidMount () {
const url = 'http://localhost:3001/clients/sel_all'
fetch(url)
.then(res => res.json())
.then(
result => {
console.log(result)
this.setState({
clients: result.data
})
},
error => {
this.setState({ error })
}
)
}
deleteTask (id, url = 'http://localhost:3001/clients/delete') {
return fetch(url + '/' + id, { method: 'DELETE' }).then(response =>
response.json()
)
}
render () {
const { error, clients, props } = this.state
if (error) {
return <div> Error:{error.message}</div>
} else {
return (
<div>
<h2>All Clients</h2>
<Table>
<thead>
<tr>
<th>No</th>
<th>Client Name</th>
<th>Client Address</th>
<th>Comment</th>
</tr>
</thead>
<tbody>
{clients.map(client => (
<tr key={client.id}>
<td>{client.id}</td>
<td>{client.name}</td>
<td>{client.address}</td>
<td>{client.comment}</td>
<td>
<button onClick={Hello}>View Contract</button>
<button>
<ReactToPrint
trigger={() => <button>print</button>}
content={() => this.componentRef}
/>
</button>
<button
onClick={() => {
props.editRow(client)
}}
className='button'
>
Edit
</button>
</td>
<button
onClick={() => {
this.deleteTask.bind(this)
}}
>
Dele
</button>
</tr>
))}
</tbody>
</Table>
</div>
)
}
}
}
export default clientview
I am getting an error in my code 'this.state.UserData.map' is not a function . i want get list from the database using fetch. i think i am forgetting something.
please help me remove this error. thanks in advance.
Here is my complete code to show list...
import React from 'react';
import ReactDOM from 'react-dom';
export default class FetchedData extends React.Component{
constructor(props){
super(props);
this.state={ UserData:[] };
this.headers=[
{key:1,label:'Name'},
{key:2,label:'Department'},
{key:3,label:'Marks'},
];
}
componentDidMount(){
fetch("https://www.veomit.com/test/zend/api/fetch.php")
.then(response => {
return response.json();
})
.then(result => {
this.setState({
UserData:result
})
.catch(error => {
console.log(
"An error occurred while trying to fetch data from Foursquare: " +error
);
});
});
}
render(){
return(
<div>
<table className="table table-bordered">
<thead>
<tr>
{
this.headers.map(function(h) {
return (
<th key = {h.key}>{h.label}</th>
);
})
}
</tr>
</thead>
<tbody>
{
this.state.UserData.map(function(item){
return (
<tr>
<td>{item.name}</td>
<td>{item.department}</td>
<td>{item.marks}</td>
</tr>
);
})
}
</tbody>
</table>
</div>
);
}
}
````````
Please replace your code I hope it's working for you.
Thanks
import React from 'react';
import ReactDOM from 'react-dom';
export default class FetchedData extends React.Component{
constructor(props){
super(props);
this.state={ UserData:[] };
this.headers=[
{key:1,label:'Name'},
{key:2,label:'Department'},
{key:3,label:'Marks'},
];
}
componentWillMount() {
fetch("https://www.veomit.com/test/zend/api/fetch.php")
.then(response => {
return response.json();
})
.then(result => {
this.setState({
UserData: result
});
})
.catch(function(error) {
console.log(
"An error occurred while trying to fetch data from Foursquare: " +
error
);
});
}
render(){
return(
<div>
<table className="table table-bordered">
<thead>
<tr>
{
this.headers.map(function(h) {
return (
<th key = {h.key}>{h.label}</th>
);
})
}
</tr>
</thead>
<tbody>
{ this.state.UserData.length > 0 ?
this.state.UserData.map((item,index) => (
<tr key={index}>
<td>{item.name}</td>
<td>{item.department}</td>
<td>{item.marks}</td>
</tr>
))
) : (
<tr>
<td colspan="3">No record found.</td>
</tr>
)}
</tbody>
</table>
</div>
);
}
}
````````
The data is an object - you need to convert it to an array with Object.values:
UserData: Object.values(result)
response is not array. You need convert response server to array of object to use map
response must like this. You can tell backend services to change like this or you convert like this to your state
[{name: 'John Doe', department: 'CEO', marks: 'title' } , {....} ]
I have implement React app getting database from MongoDB with Express Server.
For Pagination function is working well but when I implement search function is working only when typing in the input box. If I delete the character, it should search again but it is still.
Could anybody please help to verify my code??
IssueList.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import 'whatwg-fetch';
import Pagination from '../components/Pagination';
import IssueAdd from '../components/IssueAdd';
class IssueList extends Component {
constructor(props) {
super(props);
this.state = {
issues: [],
pageOfItems: [],
};
this.createIssue = this.createIssue.bind(this);
this.onChangePage = this.onChangePage.bind(this);
this.filterList = this.filterList.bind(this);
}
componentDidMount() {
this.loadData();
}
loadData() {
fetch('/api/issues').then(response => {
if (response.ok) {
response.json().then(data => {
data.records.forEach(issue => {
issue.created = new Date(issue.created);
if (issue.completionDate) {
issue.completionDate = new Date(issue.completionDate);
}
});
this.setState({ issues: data.records });
});
} else {
response.json().then(error => {
alert(`Failed to fetch issues ${error.message}`);
});
}
}).catch(err => {
alert(`Error in fetching data from server: ${err}`);
});
}
onChangePage(pageOfItems) {
this.setState({ pageOfItems: pageOfItems });
}
filterList = (e) => {
var updatedList = this.state.issues;
updatedList = updatedList.filter((item) => {
return item.title.toLowerCase().search(e.target.value.toLowerCase()) !== -1;
});
this.setState({ issues: updatedList });
}
render() {
return (
<div>
<h1>Issue Tracker</h1>
<hr />
<div className="filter-list">
<form>
<fieldset className="form-group">
<legend>Search</legend>
<input
type="text"
className="form-control form-control-lg"
placeholder="Search"
onChange={this.filterList}
/>
</fieldset>
</form>
</div>
<div className="panel panel-default">
<table className="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Status</th>
<th>Owner</th>
<th>Created</th>
<th>Effort</th>
<th>Completion Date</th>
<th>Title</th>
</tr>
</thead>
<tbody>
{this.state.pageOfItems.map(issue => (
<tr key={issue._id}>
<td>{issue._id}</td>
<td>{issue.status}</td>
<td>{issue.owner}</td>
<td>{issue.created.toDateString()}</td>
<td>{issue.effort}</td>
<td>{issue.completionDate ? issue.completionDate.toDateString() : ''}</td>
<td>{issue.title}</td>
</tr>
))}
</tbody>
</table>
</div>
<Pagination
items={this.state.issues}
onChangePage={this.onChangePage}
/>
<hr />
<IssueAdd createIssue={this.createIssue} />
</div>
);
}
}
export default IssueList;
Edited
I've tried to add loadData() function to the filterList()
filterList = (e) => {
this.loadData();
var updatedList = this.state.issues;
updatedList = updatedList.filter((item) => {
return item.title.toLowerCase().search(e.target.value.toLowerCase()) !== -1;
});
this.setState({ issues: updatedList });
}
It can search but after that it goes back to the initial state (page 1).
you need to add the value parameter to your input in order to control it's value. This could be your issue. I updated this to include adding a holder in state that holds the unfiltered array.
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import 'whatwg-fetch';
import Pagination from '../components/Pagination';
import IssueAdd from '../components/IssueAdd';
class IssueList extends Component {
constructor(props) {
super(props);
this.state = {
issues: [],
holder: [],
pageOfItems: [],
};
this.createIssue = this.createIssue.bind(this);
this.onChangePage = this.onChangePage.bind(this);
this.filterList = this.filterList.bind(this);
}
componentDidMount() {
this.loadData();
}
loadData() {
fetch('/api/issues').then(response => {
if (response.ok) {
response.json().then(data => {
data.records.forEach(issue => {
issue.created = new Date(issue.created);
if (issue.completionDate) {
issue.completionDate = new Date(issue.completionDate);
}
});
this.setState({ issues: data.records, holder: data.records });
});
} else {
response.json().then(error => {
alert(`Failed to fetch issues ${error.message}`);
});
}
}).catch(err => {
alert(`Error in fetching data from server: ${err}`);
});
}
onChangePage(pageOfItems) {
this.setState({ pageOfItems: pageOfItems });
}
filterList = (e) => {
let { value } = e.target
this.setState({ value }, () => {
//running this after setting the value in state because of async
var updatedList = this.state.holder;
updatedList = updatedList.filter((item) => {
return item.title.toLowerCase().search(this.state.value.toLowerCase()) !== -1;
});
this.setState({ issues: updatedList });
})
}
render() {
return (
<div>
<h1>Issue Tracker</h1>
<hr />
<div className="filter-list">
<form>
<fieldset className="form-group">
<legend>Search</legend>
<input
type="text"
className="form-control form-control-lg"
placeholder="Search"
value={this.state.value}
onChange={this.filterList}
/>
</fieldset>
</form>
</div>
<div className="panel panel-default">
<table className="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Status</th>
<th>Owner</th>
<th>Created</th>
<th>Effort</th>
<th>Completion Date</th>
<th>Title</th>
</tr>
</thead>
<tbody>
{this.state.pageOfItems.map(issue => (
<tr key={issue._id}>
<td>{issue._id}</td>
<td>{issue.status}</td>
<td>{issue.owner}</td>
<td>{issue.created.toDateString()}</td>
<td>{issue.effort}</td>
<td>{issue.completionDate ? issue.completionDate.toDateString() : ''}</td>
<td>{issue.title}</td>
</tr>
))}
</tbody>
</table>
</div>
<Pagination
items={this.state.issues}
onChangePage={this.onChangePage}
/>
<hr />
<IssueAdd createIssue={this.createIssue} />
</div>
);
}
}
export default IssueList;