1

In my react Component I m loading data into a table from http get.

when I delete a record, I perform delete in backend and call fetch tabledata again in react. Sometimes the deleted row does not gets removes from table in GUI. I think need to wait till the delete is performed so that i fetch table data only when i know the row got deleted.

my delete function:

handleBtnClick_RecordDeletion(e) {
    this.httpDeleteJson(this.state.ip + /delete?id=" + e.name);
    alert("Row deleted Successfully");
    this.setState({ lastDeletedRow: e.name })
    this.httpGetAll(this.state.moduleName, this);
}
Tomasz Mularczyk
  • 34,501
  • 19
  • 112
  • 166
DadyByte
  • 894
  • 6
  • 18
  • 30

1 Answers1

2

Try to use callback after setState like here:

this.setState({ lastDeletedRow: e.name }, ()=>{
     this.httpGetAll(this.state.moduleName, this);
});

Explanation:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

Source: https://vasanthk.gitbooks.io/react-bits/patterns/19.async-nature-of-setState.html

P.S. Also, there is useful referece in the duplicate mark

DanilGholtsman
  • 2,354
  • 4
  • 38
  • 69
  • "..can potentially return the *existing value*" — i don't think we need an updated value of `this.state.lastDeletedRow` to make that request – Iv Ov Nov 26 '19 at 14:47
  • I think the issue was only in the concurrency between " this.httpDeleteJson () ' and ' this.httpGetAll ()`: the deletion command can wait for batabase table lock or something, so the "get all" request get some data before the deletion actually occurs. The solution is, for example, to return a Promise from this.httpDeleteJson() and call this.httpGetAll in `.then()` – Iv Ov Nov 26 '19 at 15:01