0. Problem
app.post('/api/rate', (req,res) => {
const {residentName, quality, diff, willing, comment, tags} = req.body;
let id = 0;
db.query(`SELECT id FROM resident WHERE name = ?;`, [residentName],(err,result)=>{
if(err) throw err;
console.log(result);
id = result[0].id;
});
const query = `INSERT INTO rate(resident_id, quality_rate, difficulty_rate, willingness, comment${tagQueryFront} VALUES (${id}, ${quality}, ${diff}, '${willing}', '${comment}'${tagQueryBack}`;
}
This is the original code when I faced the problem. What I wanted to do was to retrieve 'id' and there was no way 'residentName' was wrong value since any code lines never touchned or variated it after 'residentName' first gotten from table. No syntax error either. I couldn't get anything for 'id' and I'd like to share how I solved this.
1. Callback
As I said, I got nothing and it could not happen. And eventually I found out the key was callback handling.
1-1. db.query()
The function 'query()' is asynchronous. That was the reason why I got nothing because before the query has completed, id won't be updated. Therefore, when I tried to access 'id', it wasn't supposed to be available because the query were still on the process to fetch data.
2. Fixed code
db.query(`SELECT id FROM resident WHERE name = ?;`, [residentName],(err,result)=>{
if(err) {
console.error(err);
return res.status(500).json({ error: 'Failed to retrieve resident ID.' });
}
const id = result[0]?.id;
if (!id)
return res.status(400).json({ error: 'Resident not found.' });
const query = `INSERT INTO rate(resident_id, quality_rate, difficulty_rate, willingness, comment${tagQueryFront} VALUES (${id}, ${quality}, ${diff}, '${willing}', '${comment}'${tagQueryBack}`;
db.query(query, (err, result) => {
if (err) throw err;
res.send('Rate has been added successfully!');
});
});
const id = result[0]?.id: the character '?' allows you to see "undefined" msg instead of error msg when one occurs.
tagQueryBack and tagQueryFront is defined above this code.
'Project > Rate My Resident' 카테고리의 다른 글
| 4. Using Variables in useEffect (useEffect에서 변수 쓰기) (0) | 2023.03.16 |
|---|---|
| 3. Spread Operator (Managing Array State) (0) | 2023.03.02 |
| 2. Connect Node.js to React.js with Express and Mysql (0) | 2023.01.02 |
| 1. How to put props to a page with enter key (엔터키 눌렀을 때 페이지로 인자 넘겨주기) (0) | 2022.12.31 |
| 0. Motivation / Folder Structure (0) | 2022.12.24 |