The edit functionality

We will implement the edit functionality by adding the Edit button to each table row. When the row edit button is pressed, it opens the modal form, where the user can edit the existing car and finally save their changes: 

  1. First, we will create a skeleton of the EditCar component, which will be the form for editing an existing car. Create a new file called EditCar.js in the components folder. The EditCar component code is similar to the AddCar component, but for now, in the handleSave function, we should call the update function that we will implement later:
import React, { useState } from 'react';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogTitle from '@material-ui/core/DialogTitle';

const EditCar = (props) => {
const [open, setOpen] = useState(false);
const [car, setCar] = useState({brand: '', model: '', year: '', color: '', price: ''});

const handleClickOpen = () => {
setOpen(true);
};

const handleClose = () => {
setOpen(false);
};

const handleChange = (event) => {
setCar({...car, [event.target.name]: event.target.value});
}

// Update car and close modal form
const handleSave = () => {
}

return (
<div>
<button onClick={handleClickOpen}>Edit</button>
<Dialog open={open} onClose={handleClose}>
<DialogTitle>Edit car</DialogTitle>
<DialogContent>
<input type="text" placeholder="Brand" name="brand"
value={car.brand} onChange={handleChange}/><br/>
<input type="text" placeholder="Model" name="model"
value={car.model} onChange={handleChange}/><br/>
<input type="text" placeholder="Color" name="color"
value={car.color} onChange={handleChange}/><br/>
<input type="text" placeholder="Year" name="year"
value={car.year} onChange={handleChange}/><br/>
<input type="text" placeholder="Price" name="price"
value={car.price} onChange={handleChange}/><br/>
</DialogContent>
<DialogActions>
<button onClick={handleClose}>Cancel</button>
<button onClick={handleSave}>Save</button>
</DialogActions>
</Dialog>
</div>
);
};

export default EditCar;
  1. To update the car data, we have to send the PUT request to the http://localhost:8080/api/cars/[carid] URL. The link will be the same as it is for the delete functionality. The request contains the updated car object inside the body, and the 'Content-Type': 'application/json' header that we had in the add functionality. Create a new function called updateCar in the Carlist.js file. The source code of the function is shown in the following code snippet. The function gets two arguments—the updated car object and the request URL. Following a successful update, we will show a toast message to the user:
// Carlist.js file
// Update car
updateCar(car, link) {
fetch(link,
{ method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(car)
})
.then(res => {
toast.success("Changes saved", {
position: toast.POSITION.BOTTOM_LEFT
});
this.fetchCars();
})
.catch(err =>
toast.error("Error when saving", {
position: toast.POSITION.BOTTOM_LEFT
})
)
}
  1. Next, we will import the EditCar component into the CarList component so that we are able to show it in the car list. Add the following import to the CarList.js file:
import EditCar from './EditCar';
  1. Now, add the EditCar component to the table columns in the same way that we did with the delete functionality. Now, the EditCar component is rendered to table cells and it only shows the Edit button. This is because the modal form is not visible before the button is pressed. When the user presses the Edit button, it sets the open state value to true in the EditCar component, and the modal form is shown. We pass four props to the EditCar component. The first props is row, which contains all the values from the row as an object (=car object). The second argument is value, which is set to be _links.href.self, which will be the URL of the car that we need in the request. The third one is the updateCar function, which we have to call from the EditCar component in order to be able to save changes. The last one is the fetchCars function which is used for refreshing the car list following an update:
 const columns = [{
Header: 'Brand',
accessor: 'brand'
}, {
Header: 'Model',
accessor: 'model'
}, {
Header: 'Color',
accessor: 'color'
}, {
Header: 'Year',
accessor: 'year'
}, {
Header: 'Fuel',
accessor: 'fuel'
}, {
Header: 'Price (€)',
accessor: 'price'
}, {
sortable: false,
filterable: false,
width: 100,
accessor: '_links.self.href',
Cell: ({value, row}) => (<EditCar car={row} link={value}
updateCar={this.updateCar} fetchCars={this.fetchCars} />),
width: 100
}, {
sortable: false,
filterable: false,
width: 100,
accessor: '_links.self.href',
Cell: ({value}) => (<button onClick={()=>{this.onDelClick(value)}}>Delete</button>)
}]
  1. Next, we will perform the final modifications to the EditCar.js file. We get the car to be edited from the car props, which we use to populate the form with the existing car values. Change the handleClickOpen function in the EditCar.js file. Now, when the form is opened, the car state is updated with the values from the car props:
  const handleClickOpen = () => {
setCar({brand: props.car.brand, model: props.car.model, color: props.car.color,
year: props.car.year, fuel: props.car.fuel, price: props.car.price })
setOpen(true);
}
  1. Finally, we will change the handleSave function and call the updateCar function using props:
// Update car and close modal form
const handleSave = () => {
props.updateCar(car, props.link);
handleClose();
}
  1. If you press the Edit button in the table, it opens the modal edit form and shows the car from that row. The updated values are saved to the database when you press the Save button:

Now, we have implemented all CRUD functionalities in relation to our frontend. In Chapter 12, Styling the Frontend with React Material-UI, we will focus on styling the frontend.

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

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