Product List for {this.props.name}
{this.state.products.map((productDetails, i) =>
product = {productDetails} />)}
Name
Type
Brand
Description
Edit
Delete
View
);
}
}
export default ProdosTable;
Now, if you start the React app with the npm start command, you will see the following list page:
Figure 9.2: Rendering a product list fetched from a REST API.
As you can see in the preceding screenshot, our front-end application rendered a product list that is fetched from the REST API.
Posting data using the Fetch API
In the previous section, we fetched a list of products and rendered it using the React component. Now in this section, we will create a new product
and send it to the server using the REST API and React component.
We will create a React component that is a file called ProdosForm.js and write the component code for this file as shown in the following code:
import React, { Component } from ‘react’;
class ProdosForm extends Component {
render() {
return (
//Add product form
);
}
}
export default ProdosForm;
Now, we will add a state that contains all the product-related fields and these fields will be passed to the server using the REST API:
import React, { Component } from ‘react’;
class ProdosForm extends Component {
constructor(props) {
super(props);
this.state = {id: ‘’, name: ‘’, brand: ‘’,type: ‘’, description: ‘’};
};
render() {
return (
//Add product form
);
}
}
export default ProdosForm;
As you can see, we added a state for product-related fields, and now we will add an HTML form that contains the input fields needed to collect the
product data. All input fields should have the name attribute with a value that is the same as the name of the state the value will be saved to. Input
fields also have the onChange handler, which saves the value to the state by invoking the inputChanged() function:
import React, { Component } from ‘react’;
class ProdosForm extends Component {
constructor(props) {
super(props);
this.state = {id: ‘’, name: ‘’, brand: ‘’,type: ‘’, description: ‘’};
};
inputChanged = (event) => {
this.setState({[event.target.name]: event.target.value});
};
render() {
return (
ID:
{this.state.id}/
Name:
{this.state.
Brand:
{this.state.
Type:
{this.state.
Description:
{this.state.
”Create
);
}
}
export default ProdosForm;
As you can see in the HTML form in the React component, we called a handleSubmit() function while submitting the form using onSubmit function.
Let us implement the handleSubmit() function to the ProdosForm.js file that will send the POST request to the backend prodos/products endpoint.
The request will include the new product object inside the body and the ‘Content-Type’: ‘application/json’ header. The header is needed because
the product object is converted to the JSON format using the JSON. stringify() method:
import React, { Component } from ‘react’;
class ProdosForm extends Component {
constructor(props) {
super(props);
this.state = {id: ‘’, name: ‘’, brand: ‘’,type: ‘’, description: ‘’};
};
inputChanged = (event) => {
this.setState({[event.target.name]: event.target.value});
};
handleSubmit = (event) => {
event.preventDefault();
var newProduct = {id: this.state.id, name: this.state.name, brand: this.state.brand,
type: this.state.type, description: this.state.description};
const myHeaders = new Headers({
‘Content-Type’: ‘application/json’,
‘Accept’: ‘application/json’
});
// Add new product
fetch(‘ http://localhost:8181/prodos/products ’,
{
method: ‘POST’, mode: ‘no-cors’, body: JSON.stringify(newProduct),
headers:myHeaders,
})
.then(response => console.log(‘Success:’, JSON.stringify(response)))
.catch(error => console.error(‘Error:’, error));
};
render() {
return (
ID:
{this.state.id}/
Name:
{this.state.
Brand:
{this.state.
Type:
{this.state.
Description:
{this.state.
”Create
);
}
}
export default ProdosForm;
Now, we added a React component to our front-end Prodos application to add a new product. We will start the front-end application as shown in
the following screenshot:
Figure 9.3: Rendering a Product Form to add a new product
As we have added a product form in the HTML web page, let us add a new product by clicking on the Create Product button. In the following
screenshot, you can see a new product being added to the product list:
Figure 9.4: A new product is added to the product list.
In the preceding screenshot of the product list, the last product added a new product using the React component and REST API POST
http://localhost:8181/prodos/ products. We saw how to add a new product using the REST API with the React-based front-end application. Now, we
will see how to edit the information for an existing product.
Editing data using the Fetch API
To update the product data, we need to send a PUT HTTP request to the http://localhost:8181/prodos/products/ {productId} URL. You need to
send the updated product object at the time calling this REST API. The HTTP PUT request contains the updated product data either inside the
form data or request body.
The product form structure is similar to the add product functionality. Here is the code that needs to be added to update the product data in the
server:
handleUpdate = (event) => {
event.preventDefault();
var updatedProduct = {id: this.state.id, name: this.state.name, brand: this.state.brand,
type: this.state.type, description: this.state.description};
const myHeaders = new Headers({
‘Content-Type’: ‘application/json’,
‘Accept’: ‘application/json’
});
//Update a product
fetch(‘ http://localhost:8181/prodos/products/ ’+this.state.id,
{
method: ‘PUT’, mode: ‘no-cors’, body: JSON.stringify(updatedProduct),
headers:myHeaders,
})
.then(response => console.log(‘Success Updated:’, JSON.stringify(response)))
.catch(error => console.error(‘Error:’, error));
};
The preceding code is needed to update the product data. We will update the description of the newly added product in the earlier section with the
product ID (MOB910). We will update this product with a new description of the product. Let’s see the following screenshot to update the product
data:
Figure 9.5: Rendering a Product Form to update the product data
As you can see in the preceding screenshot, we updated a product with the product ID (MOB910), which was created in the previous section. In
this product, we are only updating the product description. Click on the Update Product button and see the following updated product list:
Figure 9.6: A product is updated into the product list
In the preceding screenshot, you can see the updated description of the product with the product ID (MOB910). Now, we can add the delete
functionality in our Prodos front-end application.
Deleting data using the Fetch API
Now, we will implement the delete functionality in our Prodos application. Products can be deleted from the database by sending the DELETE
HTTP request to the REST API http://localhost:8181/prodos/products/ {productId}. In the product list, we have a link to delete a product; we can
implement the handleDeleteClick() function as shown in the following code:
handleDeleteClick = (id) => {
// Delete the product
fetch(‘ http://localhost:8181/prodos/products/ ’+id,
{
method: ‘DELETE’,
})
.then(response => console.log(‘Success Deleted:’, JSON.stringify(response)))
.catch(error => console.error(‘Error:’, error));
};
We added the preceding code to the ProdosTableRow.js file, and one more change is required to call this method when anyone clicks on the
delete link in the table list:
import React, { Component } from ‘react’;
class ProdosTableRow extends Component {
handleDeleteClick = (id) => {
// Delete the product
fetch(‘ http://localhost:8181/prodos/products/ ’+id,
{
method: ‘DELETE’,
})
.then(response => console.log(‘Successful Deleted:’))
.catch(error => console.error(‘Error:’, error));
};
render() {
return (
{this.props.product.name}
{this.props.product.type}
{this.props.product.brand}
{this.props.product.description}
Edit
{this.handleDeleteClick(this.props.product.id)}} >Delete
View
);
}
}
export default ProdosTableRow;
We need to click on the delete link in the product list and the product will be deleted. Then, refresh the product list again to see the updated
product list as shown in the following screenshot:
Figure 9.7: An updated product after deleting some products.
You can see the updated product list. We deleted some products by clicking on the delete link corresponding to each row of the table. We
implemented the CRUD functionality using React and the REST API. In the next section, we will explore some third-party React components, and
we will use them in our Prodos front-end application to beautify our UI.
Using third-party React components in our application
In this section, we will use third-party React components to make an interactive UI. First, we will use the React Table component instead of a
traditional HTML table.
Using the ReactTable
Earlier, we have used the HTML table and rendered the product list in the web page. Now, we will use the ReactTable component. It is a featured
React component and provides a lot of interactive UI features such as pagination, sorting, filtering, and more.
We will install the ReactTable component in our Prodos front-end application by using the following command.
npm install react-table --save
Now, let us update the code of the ProdosTable.js file:
import React, { Component } from ‘react’;
import ReactTable from “react-table”;
import {API
SERVER
URL} from ‘./constants.js’
import ‘react-table/react-table.css’;
import ‘./App.css’;
class ProdosTable extends Component {
constructor(props) {
super(props);
this.state = {
products: [
]
};
}
componentDidMount() {
fetch(API
SERVER
URL+’/prodos/products’, {mode: ‘cors’})
.then((response) => response.json())
.then((responseData) => {
this.setState({
products: responseData.products,
});
})
.catch(err => console.error(err));
}
render() {
const columns = [{
Header: ‘Name’,
accessor: ‘name’
}, {
Header: ‘Type’,
accessor: ‘type’,
}, {
Header: ‘Brand’,
accessor: ‘brand’,
}, {
Header: ‘Description’,
accessor: ‘description’,
},]
return (
Do'stlaringiz bilan baham: |