javascript - Updating function level variable in a fetch request -
i new fetch , react.js , javascript, trying create new row in table , id (second then), problem temp in domain changing not changing outside although defined function level variable
handleaddrow({ newrowindex }) { var temp = null; /////////////////////////////////////// updating records in db fetch(`${config.serverurl}/criteriaapi`, { method: "post", datatype: 'json', headers: { 'accept': 'application/json; charset=utf-8', 'content-type': 'application/json; charset=utf-8' } }) .then(function(res){ return res.json(); }) .then(function(data){ temp = data._id ;alert(temp)}) ////////////////////////////////////// console.log(temp); const newrow = { _id: temp, criteria_id: '', securitycriteria: '', description: '', }; let rows = this.state.rows.slice(); rows = update(rows, {$push: [newrow]}); }, console.log(temp) = > null alert(temp) = > id key : id value
it looks problem calling console.log(temp) without waiting previous promises complete, execution has not yet come point assign value temp variable. value of temp variable change - happens time after console.log(temp) gets executed.
if want use temp variable , filled in asynchronous manner - must access in corresponding then handlers.
Comments
Post a Comment