I want to list my code. I listed single query BUT the query i want to list is joined query.
app.get('/dormitory1', (req, res)=>{
client.query(`Select * from dormitory1`, (err, result)=>{
if(!err){
res.send(result.rows);
}
});
})
this is my get request, database code
import React, { useEffect, useState } from 'react'
import UpdateDormitory from './UpdateDormitory';
const ListDormitory = () => {
const[dormitory1,setDormitory1]=useState([])
const deletedormitory = async id => {
try {
const deletedormitory = await fetch(`http://localhost:2103/dormitory1/${id}`, {
method: "DELETE"
});
setDormitory1(dormitory1.filter(dormitory1=> dormitory1.dormitoryid!== id));
} catch (err) {
console.error(err.message);
}
};
const getDormitory = async () => {
try {
const response = await fetch("http://localhost:2103/dormitory1");
const jsonData = await response.json();
setDormitory1(jsonData);
} catch (err) {
console.error(err.message);
}
};
useEffect(() => {
getDormitory();
}, []);
console.log(dormitory1);
return (
<>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.4.1/dist/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"></link>
{" "}
<table class="table mt-5 text-center">
<thead>
<tr>
<th>Name of Dormitory</th>
<th>Location</th>
<th>Type of Dormitory</th>
<th>Capacity</th>
<th>Current Capacity</th>
<th>Check In Time </th>
<th>Check Out Time</th>
<th>Number Of Meals</th>
<th>Phone Number</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{dormitory1.map(dormitory1 => (
<tr key={dormitory1.dormitoryid}>
<td>{dormitory1.nameofdormitory}</td>
<td>{dormitory1.locationid}</td>
<td>{dormitory1.typeofdormitory}</td>
<td>{dormitory1.capacity}</td>
<td>{dormitory1.currentcapacity}</td>
<td>{dormitory1.checkintime}</td>
<td>{dormitory1.checkouttime}</td>
<td>{dormitory1.numberofmeals}</td>
<td>{dormitory1.phone}</td>
<td>
<UpdateDormitory dormitory1={dormitory1} />
</td>
<td>
<button
className="btn btn-danger"
onClick={() => deletedormitory(dormitory1.dormitoryid)}
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</>
)
}
export default ListDormitory
and this my listing code
they're working
they're picture:enter image description here
app.get("/search", async (req, res) => {
try {
const { city,district,typeofdormitory} = req.query;
const search = await client.query(
`SELECT (dormitory1.nameofdormitory,
location.city,
location.district,
dormitory1.typeofdormitory,
dormitory1.capacity,
dormitory1.checkintime,
dormitory1.checkouttime,
dormitory1.numberofmeals,
dormitory1.phone
) FROM location
inner join dormitory1 on location.locationid=dormitory1.locationid
WHERE (city ILIKE $1 and district ILIKE $2 and typeofdormitory ILIKE $3)`,
[`%${city}%`,`%${district}%`,`%${typeofdormitory}%`]
);
res.json(search.rows);
} catch (err) {
console.error(err.message);
}
});
the query I want to list
import React, { useEffect, useState } from 'react'
const Search = () => {
const[search,setSearch]=useState([]);
const[dormitory1,setDormitory1]=useState([]);
const[location,setLocation]=useState([]);
const getSearch = async () => {
try {
const response = await fetch("http://localhost:6302/search");
const jsonData = await response.json();
setSearch(jsonData);
} catch (err) {
console.error(err.message);
}
};
useEffect(() => {
getSearch();
}, []);
console.log(search);
return (
<>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.4.1/dist/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"></link>
{" "}
<table class="table mt-5 text-center">
<thead>
<tr>
<th>City</th>
<th>District</th>
<th>Name of Dormitory</th>
<th>Type of Dormitory</th>
<th>Capacity</th>
<th>Current Capacity</th>
<th>Check In Time </th>
<th>Check Out Time</th>
<th>Number Of Meals</th>
<th>Phone Number</th>
</tr>
</thead>
<tbody>
{search.map(search => (
<tr key={search.locationid}>
<td>{search.city}</td>
<td>{search.district}</td>
</tr>
))}
{/* {search.map(dormitory1 => (
<tr key={dormitory1.dormitoryid}>
<td>{dormitory1.nameofdormitory}</td>
<td>{dormitory1.typeofdormitory}</td>
<td>{dormitory1.capacity}</td>
<td>{dormitory1.checkintime}</td>
<td>{dormitory1.checkouttime}</td>
<td>{dormitory1.numberofmeals}</td>
<td>{dormitory1.phone}</td>
</tr>
))} */}
</tbody>
</table>
</>
)
}
export default Search
I wrote this code but it doesn't work
they're picture:enter image description here
Related
My main component
Here I'm fetching data from backend and receiving it well. Here how it looks like.
And now I want to sort them by their properties like step 1, step 2. I'm using React query to fetch data but I'm not sure how to sort it. Also, I already have sorting functions. But, I don't know how to change data based on the sorting atribute.
.
import React, { useEffect, useState } from "react";
import useFetchTable from "../../../../api/table/useFetchTable";
const TableList = () => {
const { data: response, status, isLoading } = useFetchTable();
// const [sortField, setSortField] = useState("");
// const [order, setOrder] = useState("asc");
// const handleSortingChange = (accessor) => {
// const sortOrder =
// accessor === sortField && order === "desc" ? "asc" : "desc";
// setSortField(accessor);
// setOrder(sortOrder);
// handleSorting(accessor, sortOrder);
// };
// const handleSorting = (sortField, sortOrder) => {
// if (sortField) {
// const sorted = [...data].sort((a, b) => {
// if (a[sortField] === null) return 1;
// if (b[sortField] === null) return -1;
// if (a[sortField] === null && b[sortField] === null) return 0;
// return (
// a[sortField].toString().localeCompare(b[sortField].toString(), "en", {
// numeric: true,
// }) * (sortOrder === "asc" ? 1 : -1)
// );
// });
// setData(sorted);
// }
// };
if (status === "error") {
return "Error";
}
if (isLoading) {
return "Loading...";
}
console.log(response);
const Print = ({ children }) => {
return (
<span className="text-xs bg-blue-100 rounded-full px-2 py-0.5 ml-2">
{children}%
</span>
);
};
return (
<div>
<table>
<thead className="border-b-2">
<tr>
<th className="py-1">Product Name</th>
<th>Purchases</th>
<th>US</th>
<th>Ch Step 1</th>
<th>Ch Step 2</th>
<th>CVR</th>
<th> 1</th>
<th>Upsell 2</th>
<th>Upsell 3</th>
</tr>
</thead>
<tbody>
{response.data?.map((row, idx) => (
<tr key={idx}>
<td>{row.name}</td>
<td>
{row.purchases[0]} <Print>{row.purchases[1]}</Print>
</td>
<td>
{row.unique_sessions} <Print>100</Print>
</td>
<td>
{row.checkout_step_1[0]} <Print>{row.checkout_step_1[1]}</Print>
</td>
<td>
{row.checkout_step_2[0]} <Print>{row.checkout_step_2[1]}</Print>
</td>
<td>
<Print>{`${row["cvr_%"]}`}</Print>
</td>
<td>
{row.upsell_1_takes[0]} <Print>{row.upsell_1_takes[1]}</Print>
</td>
<td>
{row.upsell_2_takes[0]} <Print>{row.upsell_2_takes[1]}</Print>
</td>
<td>
{row.upsell_3_takes[0]} <Print>{row.upsell_3_takes[1]}</Print>
</td>
</tr>
))}
</tbody>
</table>
TableList
{/* {data?.map((el) => {
el.title;
})} */}
</div>
);
};
export default TableList;
So for sorting based on your column header you can create a function to handle that onClick of the particular header. Like in the below code I have used the firstName column for sorting. On clicking the first name header it will trigger the function sortByFirstName and added the sort functionality in it and updated the state of the setTableData . Hope this helps.
import React, { useEffect, useState } from 'react'
import { useQuery } from 'react-query'
import './style.css'
function Example () {
const [sorted, setSorted] = useState({ sorted: "fname", reversed: false });
const [tableData, setTableData] = useState([])
const { data } = useQuery({
queryKey: ['repoData'],
queryFn: () =>
fetch('https://dummyjson.com/users?limit=10').then(
(res) => res.json(),
),
})
useEffect(() => {
if (data) {
setTableData(data?.users)
}
}, [data])
const sortByFirstName = () => {
setSorted({ sorted: "fname", reversed: !sorted.reversed })
const tableDataCopy = [...tableData];
tableDataCopy.sort((a, b) => {
let fnameA = a.firstName.toLowerCase();
let fnameB = b.firstName.toLowerCase();
if (sorted.reversed) {
return fnameB.localeCompare(fnameA)
}
return fnameA.localeCompare(fnameB)
})
setTableData(tableDataCopy)
}
return (
<div className='h-full w-full'>
<table className='data' cellspacing="0" cellpadding="0">
<thead>
<tr>
<th onClick={ sortByFirstName }>First Name</th>
<th >Last Name</th>
<th >Gender</th>
<th >Email</th>
<th >Bloodgroup</th>
<th >Age</th>
<th > Weight</th>
<th >Maiden Name</th>
<th >Phone</th>
</tr>
</thead>
<tbody>
{ tableData?.map((row, idx) => (
<tr key={ idx }>
<td>{ row.firstName }</td>
<td>
{ row.lastName }
</td>
<td>
{ row.gender }
</td>
<td>
{ row.email }
</td>
<td>
{ row.bloodGroup }
</td>
<td>
{ row.age }
</td>
<td>
{ row.weight }
</td>
<td>
{ row.maidenName }
</td>
<td>
{ row.phone }
</td>
</tr>
)) }
</tbody>
</table>
</div>
)
}
export default Example
I have a question about a good way to solve this problem I have in React. I need to gather currencies from my own API that I've created, that works perfectly and I iterate it in my return statement of the React component. When iterating, I want to use the "item.pairs" data to use as an argument for a method call (async method) to get price information and render it. How can this be accomplished?
I added a method getCurrencyData, I tried calling that in the return statement inside the loop, but it will not work, and I have searched for this and it's not possible to do that in that way. So how can I do this?
The used code is below:
const Start = () => {
let match = useRouteMatch()
const [currencies, setCurrencies] = useState([])
const [currencyPrices, setCurrencyPrices] = useState([])
useEffect(() => {
getAllCurrencies()
}, [])
const getCurrencyData = async (ticker) => {
try {
const response = await KrakenService.getByTicker(ticker)
return Object.values(response.data.result)[0].c[0]
} catch (err) {
console.log(err)
}
}
const getAllCurrencies = async () => {
try {
const response = await CryptoCurrencyService.getAll()
setCurrencies(response.data.results)
} catch (err) {
console.log(err)
}
}
return(
<div className='Start'>
<Switch>
<Route path={`${match.path}/:currencyId`}>
test
</Route>
<Route path={match.path}>
<Container className="cc-container">
<Row>
<Table hover className="cc-table">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Price</th>
<th>24h %</th>
<th>7d %</th>
<th>Market Cap</th>
<th>Volume (24h)</th>
<th>Circulating Supply</th>
<th>Last 30 Days</th>
</tr>
</thead>
{currencies &&
currencies.map((item, index) =>
<tbody>
<tr>
<td>{index + 1}</td>
<td><Image src={item.logo} width="38" roundedCircle /> {item.name}</td>
<td>{item.pairs}</td> HERE I WANT TO FETCH DATA
</tr>
</tbody>
)
}
</Table>
</Row>
</Container>
</Route>
</Switch>
</div>
)
}
export default Start
Maybe create component for Price information?
// PriceInformation component
const PriceInformation = ({ ticker }) => {
const [priceInfo, setPriceInfo] = useState(null)
useEffect(() => {
getCurrencyData(ticker)
}, [])
const getCurrencyData = async (ticker) => {
try {
const response = await KrakenService.getByTicker(ticker)
setPriceInfo(Object.values(response.data.result)[0].c[0]);
// return Object.values(response.data.result)[0].c[0]
} catch (err) {
console.log(err)
}
}
return (
// your code for ui
)
}
// Start component
const Start = () => {
// code ...
return (
<div className='Start'>
<Switch>
<Route path={`${match.path}/:currencyId`}>
test
</Route>
<Route path={match.path}>
<Container className="cc-container">
<Row>
<Table hover className="cc-table">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Price</th>
<th>24h %</th>
<th>7d %</th>
<th>Market Cap</th>
<th>Volume (24h)</th>
<th>Circulating Supply</th>
<th>Last 30 Days</th>
</tr>
</thead>
{currencies &&
currencies.map((item, index) =>
<tbody>
<tr>
<td>{index + 1}</td>
<td><Image src={item.logo} width="38" roundedCircle /> {item.name}</td>
{ /* <td>{item.pairs}</td> HERE I WANT TO FETCH DATA */ }
<td><PriceInformation ticker={item.pairs}/></td>
</tr>
</tbody>
)
}
</Table>
</Row>
</Container>
</Route>
</Switch>
</div>
)
}
index js
const express = require("express");
const app =express();
const cors =require("cors");
const pool = require("./db");
app.use(cors());
app.use(express.json);
app.get("/data", async (req, res) => { //async to make the process fast (await)
try {
const newData= await pool.query( "SELECT * FROM interactions");
//js2xmlparser.parse('newData',newData);
} catch (err) {
console.error(err.message);
}
});
search.js
mport React,{Fragment,useEffect,useState} from "react";
import jsontoxml from "jsontoxml";
//import * as JsonToXML from "js2xmlparser";
const ListInteract =() => {
const[interactions,setinteractions] = useState([])
const getinteractions = async () => {
try {
const response = await fetch ("http://localhost:3000/data")
const data = await response.json();
// const convert= console.log(JsonToXML.parse("data", this.data));
// jsontoxml.escape(data);
console.log(data);
setinteractions(data);
} catch (err) {
console.error(err.message)
}
}
useEffect (() => {
getinteractions();
},[]); //[] it to do one
return <Fragment>
<label>drugcode</label> <input type="text" class = "mt-5"/>
<label>diseasecode</label> <input type="text"/>
<label>type</label> <input type="text"/> <button class="btn btn-success">Search </button>
<table class="table table-hover mt-5 text-center">
<thead>
<tr>
<th>ID</th>
<th>description</th>
<th>drugcode</th>
<th>deasasecode</th>
<th>type</th>
</tr>
</thead>
<tbody>
{interactions.map(interact => (
<tr key={interact.id}>
<td>{interact.id} </td>
<td>{interact.decription} </td>
<td>{interact.drugcode} </td>
<td>{interact.diseasecode} </td>
<td>{interact.type} </td>
</tr>
)
)}
</tbody>
</table>
</Fragment>
};
export default ListInteract;
i have 3 text field i put data in it drugcode&diseasecode&type *
my goal when I put the three data in text select all and show it in the table *
ex: drug code =222, diseasecode=333, type=1 in table i want all data in it
id =1 description="good" drugcode=222,diseasecode=333 type=1
after i put the data in text i have button search when i click in it
it will show me all data in the table *
*** thank you all ***
The problem is I don't know how to put effect from parent component to child component...
I'm creating sorting function.
tableSort = (event, sortKey) => {
const {data} = this.state;
data.sort((a,b) => a[sortKey].localeCompare(b[sortKey]) )
this.setState({ data })
}
and then I'm trying to render that in my table
render() {
const {data} = this.state
return (
<>
<Table>
<Thead>
<Tr>
<Th onClick={e => this.tableSort(e, 'pool number')}>Pool Number</Th>
<Th>Sender</Th>
<Th>Not Routed Reason</Th>
<Th>Sent Date Time</Th>
<Th>Requested Delivery Report Mask Text</Th>
<Th>Delivery Report Received Date Time</Th>
<Th>isUnicode</Th>
<Th>MessageUUID</Th>
</Tr>
</Thead>
{this.renderData(data)}
</Table>
</>
)
}
The child component is called in this component and it locks like this..
import React from 'react'
import { Tbody, Tr, Td } from 'react-super-responsive-table'
const TablePageList = ({data}) => {
const {poolNumber, sender, notRoutedReason, sentDateTime, requestedDeliveryReportMaskText,
deliveryReportReceivedDateTime, isUnicode, messageUUID} = data
return (
<Tbody>
<Tr>
<Td>{poolNumber}</Td>
<Td>{sender}</Td>
<Td>{notRoutedReason}</Td>
<Td>{sentDateTime}</Td>
<Td>{requestedDeliveryReportMaskText}</Td>
<Td>{deliveryReportReceivedDateTime}</Td>
<Td>{isUnicode}</Td>
<Td>{messageUUID}</Td>
</Tr>
</Tbody>
)
}
export default TablePageList
So how can I access and sort my Td from Th?
You should call the child component from parent. You didn't call any child component.
Try below code.
import child compenent url.
import TablePageList from "./TablePageList";
And then keep state data.
this.state = {
data:[]
}
Also change function setState and order data.
tableSort = (event, sortKey) => {
const {data} = this.state;
data.sort((a,b) => a[sortKey].localeCompare(b[sortKey]) )
this.setState({ data: data })
}
And call TablePageList component below </Thead>
render() {
const { data } = this.state;
return (
<Table>
<Thead>
<Tr>
<Th onClick={e => this.tableSort(e, "pool number")}>
Pool Number
</Th>
<Th>Sender</Th>
<Th>Not Routed Reason</Th>
<Th>Sent Date Time</Th>
<Th>Requested Delivery Report Mask Text</Th>
<Th>Delivery Report Received Date Time</Th>
<Th>isUnicode</Th>
<Th>MessageUUID</Th>
</Tr>
</Thead>
{data.map(element => {
<TablePageList data={element}></TablePageList>;
})}
</Table>
);
}
And then you get data and fill it.
const TablePageList = ({ data }) => {
return (
<Tbody>
<Tr>
<Td>{data.poolNumber}</Td>
<Td>{data.sender}</Td>
<Td>{data.notRoutedReason}</Td>
<Td>{data.sentDateTime}</Td>
<Td>{data.requestedDeliveryReportMaskText}</Td>
<Td>{data.deliveryReportReceivedDateTime}</Td>
<Td>{data.isUnicode}</Td>
<Td>{data.messageUUID}</Td>
</Tr>
</Tbody>
);
};
I'm working on a project, and I would like to display some data from my firebase database,
I can show some of them, but I want to display the rest of the data of my "listClients" on a box, linked to the checkbox with the id.
listClients.js it's where i map the data from the db
import React, { Component } from "react";
import * as firebase from "firebase";
import { Table, InputGroup } from "react-bootstrap";
class ListClients extends React.Component {
state = {
loading: true
};
componentWillMount() {
const ref = firebase.database().ref("listClients");
ref.on("value", snapshot => {
this.setState({ listClients: snapshot.val(), loading: false });
});
}
render() {
if (this.state.loading) {
return <h1>Chargement...</h1>;
}
const clients = this.state.listClients.map((client, i) => (
<tr key={i}>
<td>
<input id={client.id} type="checkbox" onChange={this.cbChange} />
</td>
<td>{client.nom}</td>
<td>{client.prenom}</td>
</tr>
));
const clientsAdresses = this.state.listClients.map((clientAdresse, i) => (
<tr key={i}>
<td id={clientAdresse.id}>{clientAdresse.adresse}</td>
</tr>
));
return (
<>
<Table className="ContentDesign" striped bordered hover>
<thead>
<tr>
<th></th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>{clients}</tbody>
</Table>
<Table className="ContentDesign" striped bordered hover>
<thead>
<tr>
<th>Adresse : </th>
</tr>
</thead>
<tbody>{clientsAdresses}</tbody>
</Table>
</>
);
}
}
export default ListClients;
my data :
I only want the "adresse" of the id where the checkbox is check
Thank you
ERROR :
To retrieve the adresse from the database then use the following code:
componentWillMount() {
const ref = firebase.database().ref("listClients");
ref.on("value", snapshot => {
snapshot.forEach((subSnap) => {
let address = subSnap.val().adresse;
});
});
}
First add a reference to node listClients the using forEach you can iterate and retrieve the adresse
If you want to get the adresse according to the id, then you can use a query:
const ref = firebase.database().ref("listClients").orderByChild("id").equalTo(0);