Update Table automatically when deleting the record

Asked

Viewed 308 times

0

Hello, I would like to know how to update the table automatically after deleting some record, however, every time I delete a record, I have to refresh the page again, and so I used the function setInterval(). Here’s a sample of the code...

App component:

export default class App extends Component {
   constructor(props) {
   super(props)

    this.state = {
      users: []
    }

   this.updateTable = this.updateTable.bind(this)
   this.deleteClient = this.deleteClient.bind(this)

   }

   componentDidMount() {
   this.updateTable()
   }


   updateTable() {
     setInterval(async () => {
      const response = await Axios.get('http://localhost:8080/getclients')  
      this.setState({users: response.data})

   }, 1000)

   }

Function to delete record.

   deleteClient(id) {

     Axios.post('http://localhost:8080/delete', {
       id: id
   })   
   }

   render() {
    return (    
     <Table users={this.state.users} handleClick={this.deleteClient}/>
    );
   }
  }

Table component:

export default class Table extends Component {

   render() {
    return (
        <table>
            <thead>
                <tr>
                    <th>#</th>
                    <th>Nome</th>
                </tr>
            </thead>
            <tbody>
                {this.props.users.map(user => {
                    return <tr key={user.id}>
                        <td>{user.id}</td>
                        <td>{user.nome}</td>
                        <td><button onClick={() =>

My question is about after clicking on this button, update the table automatically.

 this.props.handleClick(user.id)}>Deletar</button></td>
                    </tr>
                })}
            </tbody>
        </table>
    )
  }
}

1 answer

0

I see two possibilities:

  1. Create a copy of the status users, remove the deleted record and update the status with the new object;
  2. Make a new request every time a record is deleted, bringing the updated listing.

The first approach is less costly, and in my view it is best to have the same effectiveness.

I see no point in using setInterval in his role updateTable. That way it makes more sense to me:

async updateTable() {
    const response = await Axios.get('http://localhost:8080/getclients')  
    this.setState({users: response.data})
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.