The delete functionality

Items can be deleted from the database by sending the DELETE method request to the http://localhost:8080/api/cars/[carid] endpoint. If we look at the JSON response data, we can see that each car contains a link to itself and it can be accessed from the _links.self.href node, as shown in the following screenshot:

The following steps show how to implement delete functionality:

  1. We will create a button for each row in the table and the accessor of the button will be _links.self.href, which we can use to call the delete function that we will create soon. But first, add a new column to the table using Cell to render the button. See the following source code. We don't want to enable sorting and filtering for the button column, therefore these props are set to be false. The button invokes the onDelClick function when pressed and sends a link to the car as an argument:
  const columns = [{
Header: 'Brand',
accessor: 'brand'
}, {
Header: 'Model',
accessor: 'model',
}, {
Header: 'Color',
accessor: 'color',
}, {
Header: 'Year',
accessor: 'year',
}, {
Header: 'Price €',
accessor: 'price',
}, {
id: 'delbutton',
sortable: false,
filterable: false,
width: 100,
accessor: '_links.self.href',
Cell: ({value}) => (<button onClick={()=>{this.onDelClick(value)}}>Delete</button>)
}]
  1. Implement the onDelClick function. But first, let's take the fetchCars function out from the componentDidMount() method. That is needed because we want to call the fetchCars function also after the car has been deleted to show an updated list of the cars to the user. Create a new function, called fetchCars(), and copy the code from the componentDidMount() method into a new function. Then call the fetchCars() function from the componentDidMount() function to fetch cars initially:
componentDidMount() {
this.fetchCars();
}

fetchCars = () => {
fetch(SERVER_URL + 'api/cars')
.then((response) => response.json())
.then((responseData) => {
this.setState({
cars: responseData._embedded.cars,
});
})
.catch(err => console.error(err));
}
  1. Implement the onDelClick function. We send the DELETE request to a car link, and when the delete succeeds, we refresh the list page by calling the fetchCars() function:
// Delete car
onDelClick = (link) => {
fetch(link, {method: 'DELETE'})
.then(res => this.fetchCars())
.catch(err => console.error(err))
}

When you start your app, the frontend should look like the following screenshot, and the car disappears from the list when the Delete button is pressed:

It would be nice to show the user some feedback upon successful deletion or if there are any errors. Let's implement a toast message to show the status of deletion. For that, we are going to use the react-toastify component (https://github.com/fkhadra/react-toastify). Install the component by typing the following command into the terminal you are using:

npm install react-toastify --save

After the installation is complete, start your app and open the Carlist.js file in the editor. We have to import ToastContainer, toast, and the style sheet to start using react-toastify. Add the following import statements to your Carlist.js file:

import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';

ToastContainer is the container component for showing toast messages, and it should be inside the render() method. In ToastContainer, you can define the duration of the toast message in milliseconds using the autoClose prop. Add the ToastContainer component inside the return statement in the render() method, just after ReactTable:

return (
<div className="App">
<ReactTable data={this.state.cars} columns={columns}
filterable={true}/>
<ToastContainer autoClose={1500} } />
</div>
);

Then, we will call the toast method in the onDelClick() function to show the toast message. You can define the type and position of the message. The success message is shown when deletion succeeds, and the error message is shown in the case of an error:

// Delete car
onDelClick = (link) => {
fetch(link, {method: 'DELETE'})
.then(res => {
toast.success("Car deleted", {
position: toast.POSITION.BOTTOM_LEFT
});
this.fetchCars();
})
.catch(err => {
toast.error("Error when deleting", {
position: toast.POSITION.BOTTOM_LEFT
});
console.error(err)
})
}

Now you will see the toast message when the car has been deleted, as shown in the following screenshot:

To avoid accidental deletion of the car, it would be nice to have a confirmation dialog after the delete button has been pressed. We will implement this using the react-confirm-alert component (https://github.com/GA-MO/react-confirm-alert). If your app is running, stop the development server by pressing Ctrl + C in the terminal and type the following command to install react-confirm-alert. After installation, restart the app:

npm install react-confirm-alert --save

Import confirmAlert and the CSS file to the Carlist component:

import { confirmAlert } from 'react-confirm-alert';
import 'react-confirm-alert/src/react-confirm-alert.css'

Create a new function, called confirmDelete, that opens the confirmation dialog. If the Yes button of the dialog is pressed, the onDelClick function is called and the car will be deleted:

confirmDelete = (link) => {
confirmAlert({
message: 'Are you sure to delete?',
buttons: [
{
label: 'Yes',
onClick: () => this.onDelClick(link)
},
{
label: 'No',
}
]
})
}

Then, change the function in the Delete button's onClick event to confirmDelete:

render() {
const columns = [{
Header: 'Brand',
accessor: 'brand',
}, {
Header: 'Model',
accessor: 'model',
}, {
Header: 'Color',
accessor: 'color',
}, {
Header: 'Year',
accessor: 'year',
}, {
Header: 'Price €',
accessor: 'price',
}, {
id: 'delbutton',
sortable: false,
filterable: false,
width: 100,
accessor: '_links.self.href',
Cell: ({value}) => (<button onClick=
{()=>{this.confirmDelete(value)}}>Delete</button>)
}]

If you now press the Delete button, the confirmation dialog will be opened and the car will be deleted only if you press the Yes button:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.68.18