i cant do search in react JS and get data from PostgreSQL - javascript

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 ***

Related

listing joined query with react

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

How can I fetch the username and image from diff schema to UI?

I want to fetch the username of those people who order under the user ID. Is it possible to grab the owner of the id and render it to the UI using userId? instead of rendering the actual userId.
It came from different schema in database,
import React, { useEffect, useState } from 'react'
import { format } from 'timeago.js'
import { userRequest } from '../../requestMethod'
import './Widgetlg.css'
const WidgetLg = () => {
const Button = ({ type }) => {
return <button className={'widgetLgButton ' + type}>{type}</button>
}
const [orders, setOrders] = useState([])
useEffect(() => {
const getOrders = async () => {
//this is just a shorcut api
try {
const res = await userRequest.get('orders')
setOrders(res.data)
console.log(res.data)
} catch (error) {
console.log(error)
}
}
getOrders()
}, [])
return (
<div className="widgetLg">
<h3 className="widgetLgTitle">Latest Transactions</h3>
<table className="widgetTable">
<tr className="widgetLgTr">
<th className="widgetLgTh">Customer</th>
<th className="widgetLgTh">Date</th>
<th className="widgetLgTh">Amount</th>
<th className="widgetLgTh">Status</th>
</tr>
{orders.map((order) => (
<tr className="widgetLgTr">
<td className="widgetLgUser">
<span className="WidgetLgName"> {order.userId} </span>
</td>
<td className="widgetLgDate"> {format(order.createdAt)} </td>
<td className="widgetLgAmmount">P {order.amount} </td>
<td className="widgetLgStatus">
<Button type={order.status} />
</td>
</tr>
))}
</table>
</div>
)
}
export default WidgetLg
How can I fetch and render the owner of the given userId?
UI
As Best as can tell you need to get a joint document or join query and create a simple endpoint that you can call at once at the ui side using axios.

tried a lot but not able to make deletehandler function working. here is my code

This is my librarylist component in which i pass deletehandler function to delete the row from library management. I don't know which part of the code is causing the problem. Any helps/suggestions are welcome.
LibraryBookList.js
const LibraryBookList = (props) => {
const[database, setDatabase]=useState()
const deleteHandler = (bookdataId) => {
const newDatabase=[...database];
const index= database.findIndex((bookdata)=>bookdata.id===bookdataId)
newDatabase.splice(index,1)
setDatabase(newDatabase);
} ;
return (
<ul className={classes.list}>
{props.database.map((bookdata) =>
(<LibraryBook
key={bookdata.key}
id={bookdata.id}
bookname={bookdata.bookName}
author={bookdata.author}
publisher={bookdata.publisher}
pages={bookdata.pages}
serialno={bookdata.serialNo}
onSelect={deleteHandler}
/>
))}
</ul>
)};
here i pass deletehandler via props
LibraryBook.js
const LibraryBook = (props) => {
return (
<li>
<table className={classes.table}>
<tbody>
<tr className={classes.table_row}>
<td className={classes.row_data}>{props.serialno}</td>
<td className={classes.row_data}>{props.pages}</td>
<td className={classes.row_data}>{props.bookname}</td>
<td className={classes.row_data}>{props.author}</td>
<td className={classes.row_data}>{props.publisher}</td>
<td>
<button className={classes.delete_btn} onClick={(props.onSelect(props.id))}>
Delete
</button>
</td>
</tr>
</tbody>
</table>
</li>
export default LibraryBookList;
**BookData.js **
const BookData = (props) => {
const [isLoading, setIsLoading] = useState(true);
const [loadedLibrarydata, setLoadedLibrarydata] = useState();
useEffect(() => {
setIsLoading(true);
fetch(
"https://librarymanagement-70ab2-default-rtdb.firebaseio.com/database.json"
)
.then((response) => {
// console.log('response',response.json())
return response.json();
})
.then((data) => {
const database = [];
console.log("data", data);
for (const key in data) {
const bookdata = {
id: key,
...data[key],
};
database.push(bookdata);
}
setIsLoading(false);
setLoadedLibrarydata(database);
});
}, []);
if (isLoading) {
return (
<section>
<p>Loading.....</p>
</section>
);
}
return (
<section>
<h1>Book Data Base</h1>
<table className={classes.table}>
<thead>
<tr className={classes.table_row}>
<th className={classes.row_heading}>Serial No</th>
<th className={classes.row_heading}>Pages</th>
<th className={classes.row_heading}>Book Name</th>
<th className={classes.row_heading}>Author</th>
<th className={classes.row_heading}>Publisher</th>
</tr>
</thead>
</table>
{loadedLibrarydata && loadedLibrarydata.length && (
<LibraryBooklist database={loadedLibrarydata} />
)}
</section>
);
};
export default BookData;
NewDataBase.js
const NewDataBase = () => {
const history=useHistory();
const addDataHandler = (bookData) => {
console.log('bookData',bookData);
fetch(
"https://librarymanagement-70ab2-default-rtdb.firebaseio.com/database.json",
{
method: "POST",
body: JSON.stringify(bookData),
headers: {
"Content-type": "application/json",
},
}
).then(()=>{
history.replace('/')
})
};
return (
<section>
<DataBaseForm onAddNewData={addDataHandler} />
</section>
);
};
export default NewDataBase;
The code has a few issues: 1) props.onSelect(props.id) inside onClick. Instead you should give a referance to that function. 2) You didn't have anything in database state before you click delete button. That is why ... spread operator didn't work 3) You are displaying props.database instead of database state. That is way the changes didn't show up even after you deleted a bookdata. I also fixed some small issues. Now it is working perfectly:
// !! you can put all the code into one file and run for testing.
// !! I removed stylings as I didn't have the source
import {useState, useEffect} from 'react'
const LibraryBooklist = (props) => {
const[database, setDatabase]=useState(props.database)
const deleteHandler = (bookdataId) => {
const newDatabase=database.filter((bookdata)=>bookdata.id!==bookdataId);
setDatabase(newDatabase);
}
return (
<ul>
{database.map((bookdata) =>
<LibraryBook
key={bookdata.id}
id={bookdata.id}
bookname={bookdata.bookName}
author={bookdata.author}
publisher={bookdata.publisher}
pages={bookdata.pages}
serialno={bookdata.serialNo}
onSelect={deleteHandler}
/>
)}
</ul>
)};
const LibraryBook = (props) => {
const {id, onSelect} = props
return (
<li>
<table>
<tbody>
<tr>
<td>{props.serialno}</td>
<td>{props.pages}</td>
<td>{props.bookname}</td>
<td>{props.author}</td>
<td>{props.publisher}</td>
<td>
<button onClick={() => onSelect(id)}>
Delete
</button>
</td>
</tr>
</tbody>
</table>
</li>
)}
const BookData = (props) => {
const [isLoading, setIsLoading] = useState(true);
const [loadedLibrarydata, setLoadedLibrarydata] = useState();
useEffect(() => {
setIsLoading(true);
fetch(
"https://librarymanagement-70ab2-default-rtdb.firebaseio.com/database.json"
)
.then((response) => {
// console.log('response',response.json())
return response.json();
})
.then((data) => {
const database = [];
for (const key in data) {
const bookdata = {
id: key,
...data[key],
};
database.push(bookdata);
}
setIsLoading(false);
setLoadedLibrarydata(database);
});
}, []);
if (isLoading) {
return (
<section>
<p>Loading.....</p>
</section>
);
}
return (
<section>
<h1>Book Data Base</h1>
<table>
<thead>
<tr>
<th>Serial No</th>
<th>Pages</th>
<th>Book Name</th>
<th>Author</th>
<th>Publisher</th>
</tr>
</thead>
</table>
{loadedLibrarydata && loadedLibrarydata.length && (
<LibraryBooklist database={loadedLibrarydata} />
)}
</section>
);
};
export default BookData;

How to print/render in a table Firebase information REACT JS

Before posting I always google, youtube, forums or try to figure it by myself or even check other people questions that are similar but I'm stuck sadly.
So I'm using firestore database, the user can create a "student" and the data is the firestore is saved like this:
It saves the course, Name, school, and the UID of the person that create it. So far I have no problems importing that information to the firestore now the issue is to bring it back in a table, I do not understand why is not being printed.
The console Log is printing all the students 1 by 1 + all the students in the array (is cause is going through all the info)
Now as you can see the table is empty! and I do not understand WHY!!! Very frustrated
This are snips of the code that are relevant:
DB part:
useEffect(() => {
db.collection('usuarios').doc(user.uid).collection('estudiantes')
.get().then((snapshot) => {
(snapshot.forEach(doc => {
const data = doc.data();
estudiantes.push(data)
console.log(doc.data());
console.log(estudiantes)
}))
})
}, []);
Map/Rendering
<tbody>
{estudiantes.map((e) => (
<tr >
<td>
<input onChange = {(event) => {
let checked = event.target.checked;
}}
type="checkbox" checked = "">
</input>
</td>
<td >{e.name}</td>
<td >{e.school}</td>
<td >{e.grade}</td>
<td></td>
</tr>
))}
</tbody>
Whole Code:
import React, { useState, useEffect } from 'react'
import { auth, db } from './firebase';
import "./ListadoEstudiantes.css"
import data from "./mock-data.json"
import { useHistory } from 'react-router-dom';
import { Checkbox } from '#material-ui/core';
function ListadoEstudiantes({user}) {
const [contacts, setContacts] = useState(data);
const history = useHistory("");
const crearEstudiante = () => {
history.push("/Crear_Estudiante");
}
const realizarPedidos = () => {
history.push("/Crear_Pedidos");
}
const estudiantes = [];
useEffect(() => {
db.collection('usuarios').doc(user.uid).collection('estudiantes')
.get().then((snapshot) => {
(snapshot.forEach(doc => {
const data = doc.data();
estudiantes.push(data)
console.log(doc.data());
console.log(estudiantes)
}))
})
}, []);
return (
<div className="listadoEstudiantes">
<div className="estudiantes_container">
<h1 className = "estudiantes_container_h1">Listado de estudiantes</h1>
<button onClick={crearEstudiante} className = "crear_estudiante_boton">Crear Estudiantes</button>
<h3 className = "estudiantes_container_h3">*Para realizar su pedido seleccione a los estudiantes</h3>
<div className ="tableContainer">
<table>
<thead>
<tr className="Lista">
<th>
<input type="checkbox"></input>
</th>
<th>Nombre</th>
<th>Colegio</th>
<th>Grado</th>
<th>Accion</th>
</tr>
</thead>
<tbody>
{estudiantes.map((e) => (
<tr >
<td>
<input onChange = {(event) => {
let checked = event.target.checked;
}}
type="checkbox" checked = "">
</input>
</td>
<td >{e.name}</td>
<td >{e.school}</td>
<td >{e.grade}</td>
<td></td>
</tr>
))}
</tbody>
</table>
</div>
<div className="space" />
<button onClick={realizarPedidos} className = "crear_estudiante_boton">Realizar Pedidos</button>
<div className="space" />
</div>
</div>
)
}
export default ListadoEstudiantes
I think that's it, the user is from the Firestore database also the data that I'm importing is a fake data that I used to test the table (and renders with no issues) that can be ignored.
This is how it looks on the fake data and how it should look with the real data (THAT DOESN'T WORK! :'3)
estudiantes should be a local state of the component. Therefore, it needs to be captured as a state and use it for table data rendering as follows.
setEstudiantes is a setState function which updates the state asynchornously. Therefore, in order to check the updated state, you need to have the console.log("estudiantes: ", estudiantes) inside the render method (not after setEstudiantes(tempData)). Otherwise, you won't be able to see the updated state.
import React, { useState, useEffect } from "react";
import { auth, db } from "./firebase";
import "./ListadoEstudiantes.css";
import data from "./mock-data.json";
import { useHistory } from "react-router-dom";
import { Checkbox } from "#material-ui/core";
function ListadoEstudiantes({ user }) {
const [contacts, setContacts] = useState(data);
const [estudiantes, setEstudiantes] = useState([]);
const history = useHistory("");
const crearEstudiante = () => {
history.push("/Crear_Estudiante");
};
const realizarPedidos = () => {
history.push("/Crear_Pedidos");
};
useEffect(() => {
db.collection("usuarios")
.doc(user.uid)
.collection("estudiantes")
.get()
.then((snapshot) => {
const tempData = [];
snapshot.forEach((doc) => {
const data = doc.data();
tempData.push(data);
console.log(doc.data());
console.log("Temp Data: ", tempData);
});
setEstudiantes(tempData);
});
}, []);
console.log("estudiantes: ", estudiantes);
return (
<div className="listadoEstudiantes">
<div className="estudiantes_container">
<h1 className="estudiantes_container_h1">Listado de estudiantes</h1>
<button onClick={crearEstudiante} className="crear_estudiante_boton">
Crear Estudiantes
</button>
<h3 className="estudiantes_container_h3">
*Para realizar su pedido seleccione a los estudiantes
</h3>
<div className="tableContainer">
<table>
<thead>
<tr className="Lista">
<th>
<input type="checkbox"></input>
</th>
<th>Nombre</th>
<th>Colegio</th>
<th>Grado</th>
<th>Accion</th>
</tr>
</thead>
<tbody>
{estudiantes.map((e) => (
<tr>
<td>
<input
onChange={(event) => {
let checked = event.target.checked;
}}
type="checkbox"
checked=""
></input>
</td>
<td>{e.name}</td>
<td>{e.school}</td>
<td>{e.grade}</td>
<td></td>
</tr>
))}
</tbody>
</table>
</div>
<div className="space" />
<button onClick={realizarPedidos} className="crear_estudiante_boton">
Realizar Pedidos
</button>
<div className="space" />
</div>
</div>
);
}
export default ListadoEstudiantes;

SQL search and JavaScript .map is not a function

I have been googling around to try to solve my issue without success.
First I understand that ".map" is a method for an array, but the variable "restaurants" is in my useState. So I didn't understand why I receive the error "TypeError: restaurants.map is not a function".
I'm trying to implement a search function in a PERN app that I've been studying. This is my Search component.
Please help me understand what might be wrong. This is the full repo in case this piece of code is not enough.
Search component:
import React, { useState } from "react";
function Search() {
const [name, setName] = useState("");
const [restaurants, setRestaurants] = useState([]);
const onSubmitForm = async (e) => {
e.preventDefault();
try {
const response = await fetch(
`http://localhost:3001/api/v1/restaurants/?name=${name}`
);
const parseResponse = await response.json();
setRestaurants(parseResponse);
} catch (err) {
console.error(err.message);
}
};
return (
<>
<div className="mb-4">
<form className="form-row" onSubmit={onSubmitForm}>
<input
type="text"
name="name"
placeholder="Search"
className="form-control"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<button className="btn btn-success">Submit</button>
</form>
<table className="table my-5">
<thead>
<tr>
<th>Restaurant</th>
</tr>
</thead>
<tbody>
{restaurants.map((restaurants) => (
<tr key={restaurants.restaurants_id}>
<td>{restaurants.name}</td>
<td>{restaurants.location}</td>
</tr>
))}
</tbody>
</table>
{restaurants.length === 0 && <p>No Results Found</p>}
</div>
</>
);
}
export default Search;
File in server.js:
app.get("/api/v1/restaurants", async (req, res) => {
try {
const { name } = req.query;
const restaurants = await pool.query(
"SELECT * FROM restaurants WHERE name || ' ' ||",
[`%${name}%`]
);
res.json(restaurants.rows);
} catch (err) {
console.error(err.message);
}
});
To get rid of the javascript.mapis not a function error in your react code you have to replace tbody in your react code in the following way to handle your empty restaurants array until its state gets updated from the HTTP response.
<tbody>
{
restaurants.length > 0 && restaurants.map((restaurants) => (
<tr key={restaurants.restaurants_id}>
<td>{restaurants.name}</td>
<td>{restaurants.location}</td>
</tr>
))
}
</tbody>
Your another question related to not getting response from the backend for your postgre SQL query, you must console.log() your query and try running it on SQL interface to find the syntactical errors.

Categories

Resources