Adding data fetched from an API into a Table automatically - javascript

I am fetching data from an API using Axios. I have a listRequest() method that is a GET request to the API, the addRow() method is used to add rows to the table automatically.
I want to be able to add the rows automatically with the fetched data.
Here is my code:
import React from 'react';
import axios from "axios";
class ShipmentsTable extends React.Component{
constructor(props){
super(props);
this.state = {
shipment: {
requestType: "Request Type",
customerName: "",
email: "",
companyName: "",
}
};
this.listRequest = this.listRequest.bind();
}
listRequest = () =>{
axios.get("http://localhost:8000/app/list/")
.then((response) =>{
let result = response.data;
console.log(result);
this.setState({shipment: result.data});
}).catch((error) =>{
console.log(error);
});
}
componentDidMount(){
this.listRequest();
}
addRow = () =>{
//destructuring
const {requestType, customerName, email, companyName} = this.state.shipment;
return this.state.shipment.map((shipment, index) =>{
<tr>
<td>{requestType}</td>
<td>{customerName}</td>
<td>{email}</td>
<td>{companyName}</td>
</tr>
});
}
render(){
return(
<table className="submittedShipmentsTable">
<thead>
<tr>
<td>
<th>Request Type</th>
</td>
<td>
<th>Customer Name</th>
</td>
<td>
<th>Email</th>
</td>
<td>
<th>Company Name</th>
</td>
</tr>
</thead>
<tbody>
{/*Adding Rows Automatically*/}
{this.addRow}
</tbody>
</table>
);
}
}
export default ShipmentsTable;
Question:
I want the data fetched from the API to be added to the table in the form of a row automatically

For map to work you need an array, ie:
this.state = {
shipments: [
{
requestType: "Request Type",
customerName: "",
email: "",
companyName: ""
}
]
};
Then you can do this in your render:
<tbody>
{this.state.shipments.map((shipment, index) => this.addRow(shipment))}
</tbody>
And add row will simply return the row:
addRow = ({ requestType, customerName, email, companyName }) => {
return (
<tr>
<td>{requestType}</td>
<td>{customerName}</td>
<td>{email}</td>
<td>{companyName}</td>
</tr>
);
};

Related

How to show the specified table row data based on the filter option in react js

I am new to reactjs. I am showing the json data in the table. I also want to display only specific table row data for the specific filter option.
Here I want when noida is selected then the table should display only 2 nd 3rd row of the table.
when Moradabad is selected the it should display only first row of the table.
Here I am attaching the image which displays all the rows , please help me in this filtration logic show only on selected city.
The code is below
import React from 'react';
import './style.css';
export default class JsonDataDisplay extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [
{
id: 1,
name: 'Akshit',
city: 'Moradabad',
},
{
id: 2,
name: 'Nikita',
city: 'Noida',
},
{
id: 3,
name: 'Deeksha',
city: 'Noida',
}
],
};
}
render() {
const displaydata = this.state.data.map((info) => (
<tr>
<td>{info.id}</td>
<td>{info.name}</td>
<td>{info.city}</td>
</tr>
));
return (
<>
<FilterComponent />
<br />
<section>
<table>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>city</th>
</tr>
</thead>
<tbody>{displaydata}</tbody>
</table>
</section>
</>
);
}
}
function FilterComponent(props) {
const data = ['All', 'Noida', 'Moradabad'];
return (
<div>
<div>city</div>
<select>
{data.map((field) => (
<option>{field}</option>
))}
</select>
</div>
);
}
Few more things to do,
Define another state variable to keep the selectedCity state
this.state = {
data: [
...
...
],
selectedCity: "All"
};
Define a onChange handler function to set the selected city
setSelectedCity = (selectedCity) => {
this.setState({ selectedCity });
};
Add a filter for displaydata as below
const displaydata = this.state.data
.filter(
({ city }) =>
this.state.selectedCity === "All" || this.state.selectedCity === city
)
.map((info) => (
<tr>
<td>{info.id}</td>
<td>{info.name}</td>
<td>{info.city}</td>
</tr>
));
Pass setSelectedCity as a prop to FilterComponent
<FilterComponent setSelectedCity={this.setSelectedCity} />
Update the FilterComponent to set the selectedCity when selection changes.
function FilterComponent({ setSelectedCity }) {
const data = ["All", "Noida", "Moradabad"];
return (
<div>
<div>city</div>
<select onChange={(e) => setSelectedCity(e.target.value)}>
{data.map((field) => (
<option value={field}>{field}</option>
))}
</select>
</div>
);
}
Code Sandbox

I created a table with react but now I need to send them data from my backend, does anyone know how I can do this?

Code Table: I am creating a table that receives parameters as shown in the table header, now I need to get them from the endpoint below, how can I do the data mapping? in the endpoint it receives a date and according to this it shows the data
import React from 'react';
import { Table, Thead, Tbody, Tr, Th, Td } from 'react-super-responsive-table';
import 'react-super-responsive-table/dist/SuperResponsiveTableStyle.css';
const TableComparativeSale = ({ data }) => {
console.log(data);
return (
<Table
id="tabla-comparativa"
className="table table-striped table-bordered"
>
<Thead>
<Tr>
<Th>Id</Th>
<Th>Tienda</Th>
<Th>Tipo de Tienda</Th>
<Th>Fecha año anterior</Th>
<Th>Fecha año actual</Th>
<Th>Estado Crecimiento</Th>
<Th>Estado Crecimiento</Th>
<Th>Visitas</Th>
<Th>Boletas</Th>
<Th>Conversion</Th>
</Tr>
</Thead>
<Tbody>
{data.map((venta) => (
<Tr key={venta.id}>
<Td>{venta.id}</Td>
<Td scope="row">{venta.nombre_tienda}</Td>
<Td>{venta.tipo_tienda}</Td>
<Td>$2.395.990</Td>
<Td>$ {venta.monto_ventas}</Td>
<Td>+</Td>
<Td>43%</Td>
<Td>{venta.visitas}</Td>
<Td>{venta.boletas}</Td>
<Td>33%</Td>
</Tr>
))}
</Tbody>
</Table>
);
};
export default TableComparativeSale;
Code ENDPOINT node js and mssql
export const TableSales = async (req, res) => {
const pool = await getConnection()
try {
const {fecha} = req.body
const result = await pool.request().query(`exec [COMER].[dbo].intranet_consulta_venta_diaria '${fecha}'`)
pool.close()
res.json(result)
return res.status(200)
} catch (error) {
pool.close()
return res.status(404).json({ msg: JSON.stringify(error) });
}
}

how can i add new row my react bootstrap table

I created the table I mentioned below using React js. When I click on the button below the table, I want to add a new row to the table. I have listed the react code I wrote below. how can I do that?
My React Code
const PPP13 = (props) => {
return (
<Jumbotron>
<p className="btn-group">13- List all owners of 20% or more of the equity of the Applicant</p>
<Table striped bordered hover>
<thead>
<tr>
<th>Owner Name</th>
<th>Title</th>
<th>Ownership %</th>
<th>TIN (EIN, SSN)</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<FormControl aria-label="DDD"/>
</td>
<td>
<FormControl aria-label="DDD"/>
</td>
<td>
<FormControl aria-label="DDD"/>
</td>
<td>
<FormControl aria-label="DDD"/>
</td>
<td>
<FormControl aria-label="DDD"/>
</td>
</tr>
</tbody>
</Table>
<Button className="btn-group" name="add" value="No">
Add more owners
</Button>
</Jumbotron>
)
}
Here is what you can do. Lets say you have a Main component which will get all details.
class Products extends React.Component {
constructor(props) {
super(props);
// this.state.products = [];
this.state = {};
this.state.filterText = "";
this.state.products = [
{
id: 1,
category: 'Sporting Goods',
price: '49.99',
qty: 12,
name: 'football'
}, {
id: 2,
category: 'Sporting Goods',
price: '9.99',
qty: 15,
name: 'baseball'
}, {
id: 3,
category: 'Sporting Goods',
price: '29.99',
qty: 14,
name: 'basketball'
}, {
id: 4,
category: 'Electronics',
price: '99.99',
qty: 34,
name: 'iPod Touch'
}, {
id: 5,
category: 'Electronics',
price: '399.99',
qty: 12,
name: 'iPhone 5'
}, {
id: 6,
category: 'Electronics',
price: '199.99',
qty: 23,
name: 'nexus 7'
}
];
}
handleAddEvent(evt) {
var id = (+ new Date() + Math.floor(Math.random() * 999999)).toString(36);
var product = {
id: id,
name: "empty row",
price: "mpty row",
category: "mpty row",
qty: 0
}
this.state.products.push(product);
this.setState(this.state.products);
}
handleProductTable(evt) {
var item = {
id: evt.target.id,
name: evt.target.name,
value: evt.target.value
};
var products = this.state.products.slice();
var newProducts = products.map(function(product) {
for (var key in product) {
if (key == item.name && product.id == item.id) {
product[key] = item.value;
}
}
return product;
});
this.setState({products:newProducts});
};
render() {
return (
<div>
<ProductTable onProductTableUpdate={this.handleProductTable.bind(this)} onRowAdd={this.handleAddEvent.bind(this)} products={this.state.products} />
</div>
);
}
}
This contains the code for adding row.Then for the table do something like this.
class ProductTable extends React.Component {
render() {
var onProductTableUpdate = this.props.onProductTableUpdate;
var product = this.props.products.map(function(product) {
return (<ProductRow onProductTableUpdate={onProductTableUpdate} product={product} key={product.id}/>)
});
return (
<div>
<button type="button" onClick={this.props.onRowAdd} className="btn btn-success pull-right">Add</button>
<table className="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>price</th>
<th>quantity</th>
<th>category</th>
</tr>
</thead>
<tbody>
{product}
</tbody>
</table>
</div>
);
}
}
Now for the row Comoponent:
class ProductRow extends React.Component {
render() {
return (
<tr className="eachRow">
<td>
{this.props.product.id}
</td>
<td>
{this.props.product.price}
</td>
<td>
{this.props.product.qty}
</td>
<td>
{this.props.product.category}
</td>
</tr>
);
}
}
Working Example:
https://jsfiddle.net/mrAhmedkhan/nvgozjhy/
Ok here's my plan:
First we create a state to hold all the data for the table. I've used an object instead of an array as it's much easier to do the change handling. With arrays you always end up doing all this awkward splicing. You can always parse the object out into an array when you're ready to use it elsewhere.
Then we render out each row of the table by mapping over the entries in our table state. Note we also write the change handler inside the map, meaning we can easily use the rowId (tableData key) to set our new state when a change comes in.
Finally we plop in a button to add more rows. This has a click handler associated with it (handleAddRowClick) which counts the number of rows we have and uses this to generate a new rowId. We use the new rowId to expand the tableData state to include a new defaultRow. I defined defaultRow outside of the function, this prevents it from being redeclared on every render.
import React, { useState } from 'react'
import { Table, Input, Button } from 'reactstrap'
const defautRow = { colA: '', colB: '' }
const IncreasableTable = props => {
const [tableData, setTableData] = useState({
row1: { colA: '', colB: '' }
})
const handleAddRowClick = () => {
const extantRowsCount = Object.keys(tableData).length
setTableData(s => ({
...s,
[`row${extantRowsCount}`]: defautRow
}))
}
return (
<>
<Table>
{
Object.entries(tableData).map(([rowId, data]) => {
const handleChange = ({ target: { name, value } }) => {
setTableData(s => ({
...s,
[rowId]: {
...s[rowId],
[name]: value
}
}))
}
return (
<tr key={rowId}>
<td>
<Input name="colA" value={data.colA} onChange={handleChange}/>
<Input name="colB" value={data.colB} onChange={handleChange}/>
</td>
</tr>
)
})
}
</Table>
<Button onClick={handleAddRowClick}>Click me to add more rows</Button>
</>
)
}
export default IncreasableTable

How to render fetched data from API

I'm trying to fetch data from an API that I want to render in a table. I am following this example, and have also tried others as well:
https://blog.hellojs.org/fetching-api-data-with-react-js-460fe8bbf8f2
When I try to console.log the state I get state is undefined. When I console.log the data I receive the correct data. I know how to solve my problem with pure JavaScript, but really want to make it work this way.
import React from "react";
import Row from '../components/Row';
class Table extends React.Component {
constructor() {
super();
this.state = {
users: [],
};
this.createNewUser = this.createNewUser.bind(this);
this.deleteExistingUser = this.deleteExistingUser.bind(this);
}
componentDidMount() {
console.log("Component did mount!");
fetch("http://localhost:8080/users")
.then(response => {
return response.json();
}).then(data => {
let users = data.response.map((row) => {
return (
<tr>
<td>{row.name}</td>
<td>{row.email}</td>
<td>{row.phone}</td>
<td>{row.age}</td>
<td>
<button className="red waves-effect waves-light btn">
Delete
</button>
</td>
</tr>
);
});
this.setState({users: users});
console.log("state", this.state.users);
});
}
render() {
return (
<table id="" className="highlight centered">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Age</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="table_body">
{this.state.users}
</tbody>
</table>
);
}
}
export default Table;
Okey, so after a little tinkering i was able to solve it.
I changed from:
let users = data.response.map((row) => {
return (
<tr>
<td>{row.name}</td>
<td>{row.email}</td>
<td>{row.phone}</td>
<td>{row.age}</td>
<td>
<button className="red waves-effect waves-light btn">
Delete
</button>
</td>
</tr>
);
});
to:
let users = data.map((row) => {
return <Row key={row.email} name={row.name} email={row.email}
phone={row.phone} age={row.age}/>
});

React : How to manage state for multiple input types

Working on a POC that displays tennis player details in a page.There can be 'n' number of players displayed. The user can update information of all the players at the same time.
Written 3 components PlayersPage, PlayerTable and PlayerRow. I am little confused on how to update the state(playerData) in PlayersPage when the player information is updated in PlayerRow. Any pointer/link will be helpful.
Below is the code:
class PlayersPage extends React.Component {
constructor(props) {
super(props);
this.state = {
playerData: [
{
"dataKey": "300",
"playerFirstName": "Roger",
"playerLastName": "Federer",
"playerRanking": "1"
},
{
"dataKey": "301",
"playerFirstName": "Rafael",
"playerLastName": "Nadal"
"playerRanking": "2"
}
]
};
}
render() {
return (
<div className="container">
<PlayerTable tableData={this.state.playerData} />;
</div>
);
}
}
class PlayerTable extends React.Component {
render() {
const rows = [];
this.props.tableData.forEach((rowData) => {
rows.push(<PlayerRow key={rowData.dataKey} rowData={rowData} />);
});
return (
<div className="table-responsive">
<table className="table table-condensed">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Ranking</th>
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>
</div>
);
}
}
PlayerTable.propTypes = {
tableData: PropTypes.array.isRequired
};
class PlayerRow extends React.Component {
render() {
return (
<tr>
<td><input type="text" value={this.props.rowData.playerFirstName} /></td>
<td><input type="text" value={this.props.rowData.playerLastName} /></td>
<td><input type="text" value={this.props.rowData.playerRanking} /></td>
</tr>
);
}
}
PlayerRow.propTypes = {
rowData: PropTypes.object.isRequired
};
class PlayersPage extends React.Component {
constructor(props) {
super(props);
this.changeRecord = this.changeRecord.bind(this);
this.state = {
playerData: [
{
"dataKey": "300",
"playerFirstName": "Roger",
"playerLastName": "Federer",
"playerRanking": "1"
},
{
"dataKey": "301",
"playerFirstName": "Rafael",
"playerLastName": "Nadal",
"playerRanking": "2"
}
]
};
}
changeRecord(record, event) {
console.log(event.currentTarget.value);
console.log(record);
this.setState({
// Write your logic to update the playerDate value accordingly
});
}
render() {
return (
<div className="container">
<PlayerTable recordChangeHandler={this.changeRecord} tableData={this.state.playerData} />;
</div>
);
}
}
class PlayerTable extends React.Component {
render() {
const rows = [];
this.props.tableData.forEach((rowData) => {
rows.push(<PlayerRow recordChangeHandler={this.props.recordChangeHandler} key={rowData.dataKey} rowData={rowData} />);
});
return (
<div className="table-responsive">
<table className="table table-condensed">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Ranking</th>
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>
</div>
);
}
}
class PlayerRow extends React.Component {
render() {
return (
<tr>
<td><input type="text" onChange={this.props.recordChangeHandler.bind(this, this.props.rowData)} defaultValue={this.props.rowData.playerFirstName} /></td>
<td><input type="text" onChange={this.props.recordChangeHandler} defaultValue={this.props.rowData.playerLastName} /></td>
<td><input type="text" onChange={this.props.recordChangeHandler} defaultValue={this.props.rowData.playerRanking} /></td>
</tr>
);
}
}
ReactDOM.render(
<PlayersPage />,
document.getElementById('container')
);
Checkout the JSFiddle example you can probably emulate in your POC app.
https://jsfiddle.net/69z2wepo/86736/
Component communication can be achieved by passing data via props.
Check out this link, specifically section 3.
How do you send data from a child to its parent?
The simplest way is for the parent to pass a function to the child. The child can use that function to communicate with its parent.
The parent would pass a function to the child as a prop, like this:
<MyChild myFunc={this.handleChildFunc.bind(this)} />
And the child would call that function like so:
this.props.myFunc();
And don't forget that the child will need this function declared in its propTypes:
MyChild.propTypes = {
myFunc: React.PropTypes.func,
};

Categories