How to get a freshly Inserted Id with reactjs (Axios)? - mysql

I am trying to retrieve the Id value of a freshly Inserted row in Mysql with react Axios.
Here Is my code In node.js
app.post('/createProject', (req,res) => {
const projectName = req.body.projectName;
const tjm = req.body.tjm;
const status = req.body.status;
db.query("INSERT INTO projects (projectName, tjm, status) VALUES (?,?,?)",
[projectName, tjm, status],
(err, result) => {
if (err) {
console.log(err);
} else {
res.send("Values Inserted");
res.send(result.insertId);
console.log(result.insertId);
}
}
);
});
I try to get the insertId with a UseState hook;to use It in another Post request and store It in another table.
The post request In react:
const [id, setId] = useState();
const addProject = () => {
Axios.post("http://localhost:3001/createProject", {
projectName: projectName,
tjm: tjm,
status: "Inachevé"//Uncomplete,
}).then((res) => {
console.log("success");
setId(res.data);
});
};
I try console.log(id) but I get undefined in the console.
The post request to get the Inserted Id of the project:
const addWork = () => {
Axios.post("http://localhost:3001/createWork", {
EmpID: id_e,//I get that Id from a drop-down list
PrID: id_p,// the Id of the Inserted project who I can't get
}).then(() => {
console.log("success");
});
};
When I fill my Inputs In the frontend and send the the data (prjectName,tjm & status),the data is stored normally and the insertId consoled In the backend but I can't get it in my client side.
How I can access to insertId in the frontend and store It In another table at the same time when creating a new Project?
note: I think that I should use async/await to make addWork function wait until addProject execute but the probleme Is how to get the insertId In the frontend.

You should not use res.send() twice. You would probably want to send json, which works like the following: res.status(200).json({message: "Message",data: lastInsertedID}).
You would then need to make sure to correctly access the id in the frontend. Therefore you can print the whole json response object from on the console and make your way through the json object until you reach the id.

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 is my Axios get request getting the entire array instead row associated with the param I pass in?

I am using Axios requests to retrieve data from MySQL with an express server in between.
I have an API route of 'http://localhost:3001/find' which displays the following json when accessed:
[{"id":1,"title":"book title 1","author":"book author 1",},
{"id":2,"title":"book title 2","author":"book author 2"}]
I am trying to retrieve the singular row with the id of 1, so am doing this get request:
const searchMe = () => {
Axios.get('http://localhost:3001/find', {
params: {
"id": "1"
}
})
.then(function (response) {
console.log(response);
})
}
However when I console log the response I get both rows instead of just the one. Is is possible the param isn't getting read properly or something?
EDIT: Here is the code in my express server for handling the 'find' request:
app.get('/find', (req, res)=>{
const sqlInsert = "SELECT * FROM songs;"
db.query(sqlInsert, (err, result)=> {
res.send(result)
// console.log(result);
})
});
I know it definitely works because it is returning the data.

Retriving data from another table and inserting it into new one sequelize

I've been working on a project that involves sequelize(MySQL DB).
So I have a table "InterestRate" that takes id's from two other tables(foreign keys).
bankId is stored in "Banks" table and interId is stored in another table called "Interest".
Now I want to populate this table with Postman by sending this data:
{
"bank": "BankName",
"inter": "Interest",
"nks": "4.11",
"eks": "6.24",
"time": "36"
}
BUT I want to populate table with the primary keys of these values(if existed in their own table). E.g When I send to postman I want to check table "Banks" and search "BankName" grab its id in that table, and put it in new table. Same thing for this inter thing.
Code that I have rn is trash, I know why it doesn't work but I'm really stuck.
(req, res) => {
const bank = req.body.bank;
const type = req.body.type;
const nks = req.body.nks;
const eks = req.body.eks;
const time = req.body.time;
InterestRate.create({
bankId: bank,
interId: type,
NKS: nks,
EKS: eks,
time: time,
})
.then(() => {
res.status(200).json({ message: 'Added successfully' });
})
.catch((err) => {
res.status(500).send('Error -> ' + err);
});
};
Note that all models etc. are set up correctly, it works if I enter things manually!
Thank you!
You just need to get Bank and Interest by names and use found model instances to get their ids to create InterestRate record:
async (req, res) => {
const bank = req.body.bank;
const type = req.body.type;
const nks = req.body.nks;
const eks = req.body.eks;
const time = req.body.time;
const foundBank = await Bank.findOne({
where: {
name: bank // use a real field name instead of "name"
}
})
const foundInterest = await Interest.findOne({
where: {
name: type // use a real field name instead of "name"
}
})
if(!foundBank) {
// here should be some "res.status(...).send(...)" with error message
return
}
if(!foundInterest) {
// here should be some "res.status(...).send(...)" with error message
return
}
try {
await InterestRate.create({
bankId: foundBank.id,
interId: foundInterest.id,
NKS: nks,
EKS: eks,
time: time,
})
res.status(200).json({ message: 'Added successfully' });
catch (err) {
res.status(500).send('Error -> ' + err);
}
};

How to send Post request for each iteration of an array in Node/Express?

I have some raw json that I'm trying to send to my back end server in mysql. I'm currently trying to loop through the specific array in the json that I need and sending data from each of the children in the array via a POST request but I am getting "Cannot set headers after they are sent to the client".
app.post('/reddit-import', function (req, res) {
console.log("Route /reddit-import POST");
let data = req.body.data.children
data.forEach(child => {
let sql1 = `CALL insert_user('${child.data.author}',
'${child.data.author_fullname}');`
connection.query(sql1,
data,
function (errQuery, result) {
if (errQuery) {
console.log(errQuery);
res.json({status: "Error", err: errQuery});
res.end();
} else {
console.log("Insert ID: ", result.insertId);
res.json({status: result.insertId, err: ""});
res.end();
}
}
);
When I send the POST request, my backend gets 2 rows of data before it hits me with the error message...any ideas?
You seem to be ending your outer response in the data.forEach with a res.end(), which I’m assuming is used to indicate the end of the outer HTTP request to the client. Did you perhaps mean to use “result” there instead?
Try this if you need to keep track insert IDs:
app.post('/reddit-import', function(req, res) {
console.log("Route /reddit-import POST");
let data = req.body.data.children
const insertIds = data.map(child => {
return new Promise((resolve, reject) => {
const sql = `CALL insert_user('${child.data.author}', '${child.data.author_fullname}')`;
connection.query(sql, (err, result) => {
if (err) {
console.log(err);
return reject(err);
}
console.log("Insert ID: ", result.insertId);
return resolve(result.insertId);
});
});
});
return Promise.all(insertIds)
.then(ids => {
return res.json({
insertIds: ids
});
})
.catch(err => {
return res.status(500).json({
message: 'got query error'
});
});
});
What this basically does is that on each query, you keep track of the insert IDs. We need to use Promises because the query() function is asynchronous, meaning it runs independently and there's no other way to keep track of the data outside of its function(err, result) callback. Now we have an array of Promises which contains the insert IDs, and what's left is to send a response that this is successful. And in order to do that, we can't simply do res.json(insertIds) because insertIds is an array of Promises and we still need to extract the values. We can easily extract all data at once from an array of Promises by using Promise.all(insertIds).then(ids => ...). If you wish to send a response informing that the request is successful, do so in this then callback. Lastly and most importantly, we handle errors in a Promise chain's .catch() block. This is where you want to send a response informing the client that there are errors.
Some things that we can improve from this solution is to implement rollbacks in case we have errors, and of course validations of parameters. Unfortunately I have to leave this to the OP to implement.
Also, keep in mind you should only send a response once and only once each request.

API delete call for row from MySQL DB not work

I'd like to create api call from back-end for DELETE query from mysql DB but when execute it in browser get error
'Cannot GET ...'
I pass into the route id of row which had got from DB
At back-end the code is:
app.delete('/products/delete/:id*?', function(req, res) =>{
let { id } = req.query;
let DELETE_PRODUCT_FROM_DB = `DELETE FROM my_db.products WHERE my_db.id= '${req.query}'`;
console.log("id: ", req.query);
// delete a row with id = req.query
connection.query(DELETE_PRODUCT_FROM_DB, (error, results, fields) => {
if (error) return console.error(error.message);
res.status(200).send(results);
console.log("Deleted Row(s):", results.affectedRows);
});
});
But finally this call not works and row not deleted
let DELETE_PRODUCT_FROM_DB = `DELETE FROM my_db.products WHERE my_db.id= '${req.query.id}'`;
console.log("id: ", req.query.id);
Try using this.
fetch(url, {
method: 'delete'
}).then(response => response.json());
Try running this in your browser console. It should work.
Most likely you're making a GET call to a DELETE resource.
Please read Express 4.x. Can you share the code you're using to make DELETE request from browser?
I did some changes and now running version of the code looks like
app.delete('/products/delete/:id', (req, res) => {
let { id } = req.params ;
let DELETE_PRODUCT_FROM_DB = `DELETE FROM my_DB.products WHERE id= '${id}'`;
console.log('id: ', req.params);
// delete a row with id = req.params
connection.query(DELETE_PRODUCT_FROM_DB, (error, results, fields) => {
if (error) return console.error(error.message);
res.status(200).send(results);
console.log('Deleted Row(s):', results.affectedRows);
});
});
Also, I figured out that changes from req.query on req.params helped to get id from the link as a parameter