Do a function that makes a request to an api to delete a saved

1

I would like to know how to make functional, let's say this button, I create a table with a repeater that shows me all the categories that the api returns in json, but in each I have the option to eliminate, to eliminate that category, how can I do in react that for example with some onClick or something like that call a function and send the name of that category and then that the function makes a fetch to my API?

{this.state.items.length ?
        this.state.items.map(item=>

  <tr>
    <td>{item.name}</td>
    <td><a href="#"><b>Edit</b></a> | <a className="red" href="#">Delete</a></td>
  </tr>
    
asked by Santiago D'Antuoni 13.01.2017 в 21:26
source

1 answer

1

You can pass directly to the method responsible for deleting the category the id of it:

<button onClick={() => this.removeCategory(categoria.id)}>Eliminar</button>

You can also do it like this:

<button onClick={this.removeCategory.bind(this, categoria.id)}>Eliminar</button>

And when you click on the button, you pass the property id of the category to the method and here it is sent to the API for deletion:

removeCategory (id) {
  fetch ('http://localhost:3000/api/categorias/${id}', {
    method: 'DELETE'
  })
  .then(res => res.json())
  .then(res => {
    if (res.success) {
      let categories = this.state.categories.filter(c => c.id !== id);
      this.setState({ categories });
      alert('Categoría eliminada');
    }
  });
}

After deleting the category from the database, we have to eliminate it from the table. For this you can filter the categories that you have in the state so that you only get the categories whose id is different to the id of the deleted category:

let categories = this.state.categories.filter(c => c.id !== id);
this.setState({ categories });

What will happen is that the table will be re-rendered and the deleted record will no longer appear.

    
answered by 13.01.2017 / 22:12
source