MySQL procedure returns two unnamed arrays - mysql

Im building an app with ReactJS and MySQL database and I have a problem - the API/MySQL returns two arrays with no names.
Calling it from my API which uses MySQL (db) and Express (app)
app.get("/api/getInventory", (req, res) => {
const PlayerID = 1
const sqlSelect =
"call pInventory_select(?)"
db.query(sqlSelect, PlayerID, (err, result)=> {
//console.log(err)
res.send(result)
});
})
returns two arrays with no names:
And returning the JSON data here:
import Axios from 'axios'
import { useState, useEffect } from "react";
export default function Inventory() {
const [Inventory, setInventory] = useState([])
useEffect(() => {
Axios.get('http://localhost:3030/api/getInventory').then((response)=> {
setInventory(response.data);
})
}, [])
console.log(Inventory)
return (
<main className="text-xl font-bold text-slate-200">
<h2 className="text-3xl font-bold text-slate-200">Inventory 🎒</h2>
<table className=''>
<tr>
<th>Skin name</th>
<th>Grade</th>
<th>Wear</th>
<th>Collection</th>
<th>Price</th>
<th>Amount</th>
</tr>
{Inventory.map(item => (
<tr>
<td className='px-2'>{item.SkinName}</td>
<td className='px-2'>{item.RarityName}</td>
<td className='px-2'>{item.QualityName}</td>
<td className='px-2'>{item.CaseName}</td>
<td className='px-2'>{item.ItemPrice}</td>
<td className='px-2'>{item.Amount}</td>
</tr>
))}
</table>
</main>
);
}

Related

React.js datatable data filter by datepicker and get sum value of column

import React, { useEffect, useState } from "react";
import axios from "axios";
import { Form } from "react-bootstrap";
function SalesReport() {
const [Data, setData] = useState([]);
useEffect(() => {
fetchData();
}, []);
const fetchData = () => {
axios.get("http://localhost:4000/api/cash/showInvoices").then((res) => {
const getData = res.data.data;
setData(getData);
});
};
return (
<div className="row">
<div className="card">
<div className="card-body">
<div className="d-inline-flex col-2 m-2">
<Form.Group controlId="dob">
<Form.Label>Start Date</Form.Label>
<Form.Control
type="date"
name="startDate"
placeholder="Date of Birth"
/>
</Form.Group>
<div className="ms-3">
<Form.Group controlId="dob">
<Form.Label>End Date</Form.Label>
<Form.Control
type="date"
name="enddate"
value={}
placeholder="Date of Birth"
/>
</Form.Group>
</div>
<div className="ms-2 mt-4">
<button className="btn btn-secondary btn-lg" type="button">
Print
</button>
</div>
</div>
<table
id="datatable-buttons"
className="table table dt-responsive nowrap w-100"
>
<thead>
<tr>
<th width="100px">Date</th>
<th>Invoice Id</th>
<th>Pay Method</th>
<th>Total</th>
<th>Customer Id</th>
<th>Cart Id</th>
</tr>
</thead>
<tbody>
{Data &&
Data.map((items) => {
return (
<tr>
<td> {new Date(items.date).toLocaleDateString()}</td>
<td>{items.invoice_id}</td>
<td>{items.pay_method}</td>
<td>{items.total}</td>
<td>{items.customer_id}</td>
<td>{items.inovice_cart_id}</td>
</tr>
);
})}
</tbody>
<tfoot>
<tr className="text-black font-weight-bol">
<td>
<h5 className="total-label">Grand Total</h5>
</td>
<td className="total-col">
<label></label>
</td>
<td className="total-col">
<label></label>
</td>
<td className="total-col">
<label>2234</label>
</td>
<td className="total-col">
<label></label>
</td>
<td className="total-col">
<label></label>
</td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
);
}
export default SalesReport;
**backend**
*router.js*
const {
getInvoice,
viewInvoiceByDate,
} = require("./cashManagement.controller");
const router = require("express").Router();
const cors = require("cors");
router.get("/showInvoices", getInvoice);
module.exports = router;
*controller.js*
const { getInvoice, viewInvoiceByDate } = require("./cashManagement.service");
module.exports = {
getInvoice: (req, res) => {
getInvoice((err, results) => {
if (err) {
console.log(err);
return;
}
return res.json({
success: 1,
data: results,
});
});
},
}
*service.js*
const pool = require("../../config/database");
module.exports = {
getInvoice: (callBack) => {
var todayDate = new Date().toISOString().slice(0, 10);
pool.query(
`SELECT * FROM cash_management WHERE date='${todayDate}'`,
(errors, results, fields) => {
if (errors) {
return callBack(errors);
}
return callBack(null, results);
}
);
},
}
That picture shows what I'm trying to do. by default today's relevant data show. it took from using "new Date()" method using with mysql select query . So , if I want to get particular days period data , I should select it from data picker. There is two datapickers . one for starting date, second one for end data selecting. if I select just start date , I need data from that day to today . otherwise if I select just endDate , I need to get data from today to end date . so I tried to that someways. It doesn't work properly. My backend code here ,it contains how I got data from database . I just got data from using "newDate()" method to took today data. how it should be changed when entering start date and end date . otherwise here table you can see the total column . and table footer has "GrandTotal " 4th column should get the total values of "total columns" previously I took it direct from database. but now cant , because it is changed by quickly. I think you have clear idea about issue. I tried many ways , but it didn't work. if there any expert help me to solve the issue.

How to display image from MySQL in ReactJS using Express

I have uploaded an image in the images folder of my Node server and the path is stored in the MYSQL database. I want to display the image in my ReactJS application. I am getting the error:
http://127.0.0.1:8080/images/abc.jpg 404 (Not Found)
const baseURL = "http://localhost:8080/data";
export default function Displaydata() {
const [userdata, setuserdata] = React.useState([]);
React.useEffect(() => {
axios.get(baseURL)
.then((response) => {
setuserdata(response.data);
console.log(response.data);
});
}, []);
if (!userdata) return null;
return (
<>
<h2>Data</h2>
<table border="1">
<thead>
<tr>
<th>S.No</th>
<th>userid</th>
<th>Name</th>
</tr>
</thead>
<tbody>
{userdata.map(({ userid, name,image },index) => {
let sno=0;
return (
<tr key={userid}>
<td>{index + 1}</td>
<td>{userid}</td>
<td>{name}</td>
<td><img src={image} alt={image}/></td>
</tr>
);
})}
</tbody>
</table>
</>
);
}
What can I try to fix this?

How can I update my input to make sure it has the latest value

I have a react component called productsTable where a user can specify the number of products they want for an item and then add it to their cart. I am using a input field to allow them to enter the number of products. The issue I am having is that if a user enters the values for the input fields and clicks add to cart for each product, the value that setState will have is the last value entered in the input field vs having that individual input fields value. The reason this happens is the way I am using setState which is updated in the onChange of the input. Any idea on what I can do to fix this. I was thinking maybe putting the input as it's own seperate component so each product can get it's own instance of an input. Code is down below.
import { Table, Button } from 'react-bootstrap';
import { useDispatch, useSelector } from 'react-redux';
import { useEffect, useState } from 'react';
import { getAllProducts } from '../../redux/actions/productActions';
import { sortBy } from 'lodash';
import { toast } from 'react-toastify';
import { addToCart } from '../../redux/actions/shoppingCartActions';
const ProductsTable = ({ searchTerm }) => {
const userInfo = JSON.parse(localStorage.getItem('userInfo')) || {};
const dispatch = useDispatch();
const [input, setInput] = useState(0);
const cartId = useSelector((state) => state.cartStatus.cartInfo.cartId);
const handleAdd = (product, input) => {
const isBadInput = validateInput(input);
if (isBadInput) {
toast.error('Invalid product amount', {
position: toast.POSITION.TOP_CENTER,
autoClose: 1200,
});
return;
}
const myProduct = {
productAmount: input,
...product,
userId: userInfo.userId,
cartId: cartId,
};
dispatch(addToCart(myProduct));
toast.success('Product added successfuly', {
position: toast.POSITION.TOP_CENTER,
autoClose: 1500,
});
};
useEffect(() => {
dispatch(getAllProducts());
}, []);
const products = useSelector((state) => state.productReducer.products);
const sortedProducts = sortBy(products, ({ productName }) =>
productName.toLowerCase()
);
const validateInput = (inputValue) => {
let value = parseInt(inputValue, 10);
if (value < 0) {
return true;
} else {
value = value >= 0 ? value : 0;
setInput(value);
}
};
return (
<div className='col-9'>
<Table striped bordered hover>
<thead>
<tr>
<th>Product Name</th>
<th>Product Price</th>
<th>Seller</th>
<th>Amount In Stock</th>
<th>Amount To Purchase</th>
<th></th>
</tr>
</thead>
<tbody>
{sortedProducts.length > 0 &&
sortedProducts
.filter((product) => {
const { productName } = product;
if (searchTerm === '') {
return product;
}
if (productName.toLowerCase().includes(searchTerm)) {
return product;
}
})
.map((product) => {
return (
<tr key={product.id}>
<td>{product.productName}</td>
<td>{product.productPrice}</td>
<td>Seller </td>
<td>{product.productInStock}</td>
<td>
<input
type='number'
name='input'
step='1'
onChange={(event) => setInput(event.target.value)}
/>
</td>
<td>
<Button
onClick={() => handleAdd(product, input)}
variant='primary'
>
Add To Cart
</Button>
</td>
</tr>
);
})}
</tbody>
</Table>
</div>
);
};
export default ProductsTable;
For those of you who run into a similar issue, I moved the input field into its own component and called it in the productsTable component. That way there is a separate input field for each product. I had a feeling that would work originally but after trying on my own, I was able to prove it.

Unable to fetch object for ngFor in angular component

I am trying to show data in table using ngFor but it is unable to fetch the object that contains data in it. I called 2 services in my ngOnInit method and merged their data together using promises but i am unable to fetch that object in ngFor in my html file
html file
<table class="table table-hover table-striped">
<thead>
<tr>
<th>Date/Time</th>
<th>Course</th>
<th>Location</th>
<th>Instructor</th>
<th>Enrolled</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let obj of completeData">
<td class="trim">{{obj.date}}</td>
<td class="trim">{{obj.course}}</td>
<td class="trim">{{obj.location}}</td>
<td class="trim">{{obj.instructor}}</td>
<td class="trim">Yes</td>
<td class="trim">
<nb-select>
<nb-option value="2">Edit</nb-option>
<nb-option value="3">Delete</nb-option>
<nb-option value="4">View</nb-option>
</nb-select>
</td>
</tr>
</tbody>
</table>
component.ts file
export class UpcomingClassesComponent implements OnInit {
times: ClassTimes = new ClassTimes();
schedule: ClassSchedule = new ClassSchedule();
classes: any;
timing: any;
data: any;
completeData: any;
constructor(private router:Router,
private _classService: ClassServiceProxy) {
}
ngOnInit() {
let dataPromise = new Promise((resolve) => {
this._classService.GetClassData()
.subscribe((result: any) => {
resolve(result[0]);
})
});
let timesPromise = new Promise((resolve) => {
this._classService.GetClassTimes()
.subscribe((result: any) => {
resolve(result[0]);
})
});
Promise.all([dataPromise, timesPromise])
.then((values) => {
//console.log(values);
//let completeData = { ...values[0], ...values[1]};
this.completeData = Object.assign({}, values[0], values[1]);
//console.log(this.completeData);
//console.log("final results : ", completeData);
});
}
}
You might need to force change detection. Try the below code. NgZone
constructor(private zone: NgZone) {
//...
});
this.zone.run(() => {
this.completeData = Object.assign({}, values[0], values[1]);
});

this.state.post.map is not a function

I am receiving json data from server and i am trying to access it individually using map function in front end but i am receiving an error as this.state.post.map is not a function. below is the code how do i overcome this.
import React from 'react';
import axios from 'axios';
//require('./style.scss');
class Premontessori extends React.Component{
constructor(props){
super(props);
this.state={
post:[]
};
}
componentDidMount(){
let self = this;
axios.get('http://localhost:8080/list')
.then(function(data) {
console.log(data);
self.setState({post:data});
});
}
render(){
return (
<div>
<table>
<tbody>
{
this.state.post.map(function(item, index){
return (
<tr>
<td>{item.Id}</td>
<td>{item.Name}</td>
<td>{item.Age}</td>
</tr>
)
})
}
</tbody>
</table>
</div>
);
}
}
export default Premontessori;
From your comment,
'since this.state.post is not an array hence you get an error that map is not a function.
You need to map over the data in the post object like
<tbody>
{this.state.post.data.map(function(item, index) {
return (
<tr key={index}>
<td>{item.Id}</td>
<td>{item.Name}</td>
<td>{item.Age}</td>
</tr>
)
})
}
</tbody>
I think you have to make an adjustment in the code in the componentDidMount life-cycle method as shown below. This is because the response from the axios call is wrapping the array data, so you have to fetch that array and update your state if the status code is 200.
import React from 'react';
import axios from 'axios';
//require('./style.scss');
class Premontessori extends React.Component{
constructor(props){
super(props);
this.state={
post:[]
};
}
componentDidMount(){
let self = this;
axios.get('http://localhost:8080/list')
.then(function(res) {
console.log(res);
if(res.status === 200){
self.setState({post:res.data});
}
})
.catch(function(err){
console.log(err);
});
}
render(){
return (
<div>
<table>
<tbody>
{
this.state.post.map(function(item, index){
return (
<tr>
<td>{item.Id}</td>
<td>{item.Name}</td>
<td>{item.Age}</td>
</tr>
)
})
}
</tbody>
</table>
</div>
);
}
}
export default Premontessori;