I have a MySQL database that contains a list of customers. I am able to access this list from the server side via Express using the following code:
app.get("/customer/lookup", (req, res) => {
const sqlSelect =
"SELECT * FROM customers;";
db.query(sqlSelect, (err, result) => {
if (!err) {
console.log(result);
} else {
console.log(err);
}
});
});
I can see the JS object data displayed in my terminal, so I know my query is successful. However, I am not able to successfully make a GET request from my front-end React component. This is the code I am using:
import React, {useState, useEffect} from "react";
import axios from "axios";
import { Link, Switch, Route } from 'react-router-dom';
function LookupTable() {
const [customerList, setCustomerList] = useState([]);
useEffect(()=> {
axios.get("http://localhost:4000/customer/lookup")
.then(response => {
setCustomerList(response.data)
});
}, []);
return (
<div>
<h1>Lookup Table</h1>
{customerList.map((val)=> {
return <p>Customer: {val.fullName}</p>
})}
</div>
);
}
export default LookupTable;
I am simply trying to render that same JS object data in the browser for now, but I'm only able to render the h1 element. I have tried to console log the customerList within the useEffect function after setCustomerList(response.data)
and I see that it's an empty object.
What am I missing here?
You need to actually return the results from you server. Currently you only log them to the console.
Something like
app.get("/customer/lookup", (req, res, next) => {
const sqlSelect = "SELECT * FROM customers;";
db.query(sqlSelect, (err, result) => {
if (!err) {
console.log(result);
res.json(result);
} else {
console.log(err);
next(err);
}
});
});