Nodejs MySQL keeps returning the results - mysql

I am having this issue where the result of the MySQL query in NodeJS keeps returning the results in the console and I am wondering why is this happenning?
Here is what I have done:
Server.js
app.get("/api/listproduct", (req, res) => {
db.query("SELECT * FROM products" , (err, result) => {
if (err) {
console.log(err);
} else {
console.log(result)
res.send(result);
}
}
)
})
ShowProduct.js
useEffect(async () => {
const result = await axios.get('http://localhost:3000/api/listproduct');
console.log(result.data)
setProducts(result.data);
});
As you can see that the result are sort of looping to the console as shown here where it was supposed to just return only one set rather than many of the same sets of results.
What am I missing here and how to solve this? Many thanks in advance and greatly appreciate any helps. Thanks

This has nothing to do with the Nodejs/MySQL backend, but your frontend React code.
You don't have a dependency array in your useEffect, so it's called every time the component is rendered. Since it calls setState, it causes a new render, and effectively an infinite loop of renders. If you don't have dependencies for your effect, add an empty array to make the effect get called only once.
useEffect(async () => {
const result = await axios.get("http://localhost:3000/api/listproduct");
setProducts(result.data);
}, []); // <- that empty array

Related

Pass the dropdown selected value to NodeJS for querying database

i have created one dropdown that passes data to NodeJS through axios post i can see that in console log of nodejs Post but cant able to use the value outside the post function
i want to use the value to querying the database
my nodejs code:
app.post('/getmodel', (req, res) => {
var model = req.body.model;
console.log(model);
//It shows model value here but can't able to use outside
});
app.get('/model', (req,res)=>{
let model = req.body.model;
let sql ="select * from new_schema.model_list,new_schema.images where model_name= " + mysql.escape(model)
db.query(sql,model, (err,results) =>{
if(err){
throw err
}
console.log(results)
res.send(results);
})
})
my react code works fine as i can able to see the selected value in nodejs console below
these are the selected value from my dropdown that shows in my nodejs console. but in cant use it by req.body like that please help me
You can try like this
app.post('/getmodel', (req, res) => {
var model = req.body.model;
console.log(model);
//It shows model value here and you can able to use in the query
let sql = "select * from new_schema.model_list,new_schema.images where model_name= " + mysql.escape(model)
db.query(sql, model, (err, results) => {
if (err) {
throw err
}
console.log(results)
res.send(results);
})
});

Why does express (node.js) require params for delete request?

I made todo react app where user clicks on delete button it fetches delete request to my node.js server.
const deleteTodo = (id) => {
const q = `DELETE FROM todos WHERE id=${id}`;
connection.query(q, (err, results) => {
if (err) throw err;
console.log('delete', results)
})
}
However, when I simply went with router option below,
app.delete('/', function (req, res) {
(some function)
})
app wouldn't delete just like this.
On the other hand, by simply making it
app.delete('/todos/:id', function (req, res) {
(some function)
})
it will start functioning again.
Why is this so?
I think your question has some missing information.
In particular, how you're calling deleteTodo and what the error actually is.
If I were to make a guess, when /todos/:id is specified, it becomes possible to use req.params.id.
However, when it's /, req.params.id is undefined.
When req.params.id is undefined, the query becomes invalid.
Refer to express documentation for more details.

mySQL queries inside a for loop within a promise.resolve doesn't work

const getSelectStations = (stations => {
let query = 'SELECT * FROM stops INNER JOIN stations ON stops.station_id = stations.id WHERE stops.line_id IN (?)';
let collection = [];
const getStops = () => {
for (let i = 0; i < stations.length; i++) {
connection.query(query, [stations[i]], (err, results) => {
if (err) {
return err;
} else {
collection.push(results);
}
})
}
}
Promise.resolve(getStops())
.then(() => {
console.log('AFTERRRRRRRRRRRRR', collection); //results in initial value of []
})
.catch(err => {
console.log(err);
})
})
I've been stuck for a few hours on trying to figure this out as well as trying other methods. I feel like there's a gap in my knowledge regarding promises here. What I'm trying to do is run some mysql queries through express for a variable amount of numbers inside the stations variable. My current understanding to what I have coded is that I'm calling my getStops() function inside of a Promise.resolve() which to me means that then .then() after won't execute until that promise is resolved meaning that all my queries have been called and returned. I am pushing the result of each query into a variable called collection which is outside the scope of my getStops function. I expected my collection variable to have all the query results in the .then call but it returns []. I have consoled logged out the results from my query and they return the desired data. From what I'm seeing while I troubleshoot is that either my console.log(collection) inside of my .then is being called before the promise resolves which doesn't make sense to me leading me to think that I am incorrectly using Promise here or I have an unrelated error to my Promise.

Executing multiple queries in Nodejs route

I have Node.js post route in which I am executing several queries in sequence with async/await.
router.post("/foo", async (req, res) => {
const qr1 = "str1";
await db.query(qr1); // Works fine
const qr2 = "str2";
await db.query(qr2); // Works fine
const qr3 = "str3";
await db.query(qr3, async (err, result) => {
if (err) {
console.log(err);
}
if (result.length > 0) {
// Required data is received – That part works
// do something and continue to step 4
}
});
// step 4 – Never gets here
});
All queries which perform table manipulation i.e. delete, insert etc work fine. Once I get to a select query I receive the required data but i need to continue to the next step which doesn't happen.
I know I can accomplish what I need by nesting step 4 within step 3, but I would like to know if there is a different way to do that.
The issue you have is that comment // step 4 is executed immediately whereas the async(err code is executed asynchronously when query 3 executes. Here is your code corrected to achieve your result:
router.post("/foo", async (req, res) => {
try {
const qr1 = "str1";
await db.query(qr1); // Works fine
const qr2 = "str2";
await db.query(qr2); // Works fine
const qr3 = "str3";
const q3Result = await db.query(qr3);
console.log('step 4');
// step 4 – Should work fine
}
catch(err) {
console.log(err);
}
});

how do I access the result(object) of a get request using express?

Here is my get request made to a mysql table
app.get('/', (req, res) => {
let sql = 'SELECT * from emarttesttable WHERE id = 229';
let query = db.query(sql, (err, results) => {
if(err){console.log(err);}
else{
console.log(results);
}
});
res.render('index');
});
As it stands, this function allows me to grab the information I want from the table and I can read the results via console.log. However, I'm unable to access results on my index.ejs page.
How do I access results(which is an object that contains the stuff I want) in my index.ejs file? Whenever I try to access results, it says that results in undefined. How do I make sure that the object that is created as a result of the call to the table is able to be used/accessed on a different page. For the time being, I would just like to create a simple table that has the keys in one column and the values in a second column.
You need to modify your code as below. The reason is db.query is an async operation and you are trying to render before the async request completed. Also, to be able to reach the result at your template engine, you need to pass the results to the render. (index.ejs)
app.get('/', (req, res) => {
let sql = 'SELECT * from emarttesttable WHERE id = 229';
let query = db.query(sql, (err, results) => {
if(err){console.log(err);}
else{
res.render('index', results);
console.log(results);
}
});