Home > Enterprise >  How to use sql returning id in front-end JavaScript?
How to use sql returning id in front-end JavaScript?

Time:09-13

I have this request in server.js file.

app.post("/insertRowtoMain", (req, res) => {
  const {nodeid,  maintenancetype, personnel, process, date} = req.body;
  
  //console.log("description",description)
  let insertQuery = `insert into maintenance(nodeid,maintenancetype, personnel, process, date)
                     values(${nodeid},'${maintenancetype}',${personnel},'${process}', '${date}') returning id`

  pool.query(insertQuery, (err, result) => {
    if (!err) {
      console.log("insertRowtoMain", result.rows);
      res.status(200).send(result.rows);
    } else {
      res.status(404).json(err.message)
      console.log("insertRowtoMain error", err.message)
      
    }
  })
})

And I am calling this request function in front-end with this code:

const addNewMainTypes = async () => {
    try {
      await axios.post(`${serverBaseUrl}/insertRowtoMain`, {
        nodeid: newMaintenance.nodeid,
        maintenancetype: newMaintenance.maintenancetype,
        personnel: newMaintenance.personnel,
        process: newMaintenance.process,
        date: newMaintenance.date,
      });
    } catch (err) {
      throw err;
    }
    const maintenance = await getMain();
    // console.log("main list", maintenanceList);
    setMaintenance(maintenance);
    const maintenanceList = await getMainTypes();
    // console.log("main list", maintenanceList);
    setMaintenanceList(maintenanceList);
  };

When I insert a new row to this function, I got the returning id in server.js terminal. Terminal

How can I use that Id in front-end?

CodePudding user response:

Save the response of the POST request in a variable and access the data property

// Here, "data" will be a variable with the response data
const { data } = await axios.post(`${serverBaseUrl}/insertRowtoMain`, {
    nodeid: newMaintenance.nodeid,
    maintenancetype: newMaintenance.maintenancetype,
    personnel: newMaintenance.personnel,
    process: newMaintenance.process,
    date: newMaintenance.date,
});

/* Seems like your API is returning an array of objects with "id" property, so, for example... */
// The following should console.log the first element's id of the array
console.log(data[0]?.id);
  • Related