Crud Operation: Create Insert Delete Update Records in Reactjs
Crud Operation: Create Insert Delete Update Records in Reactjs
ReactJs.
In this lesson you can learn complete crud operation read, add, edit and delete data in React
Js using api with the help of an example. API has created in CodeIgniter and MySQL.
You can see the code explanation about this page on giving YouTube link in the bottom of
this page.
Bootstrap also installed in this tutorial. You can learn how to Integrate Bootstrap with React
Js
Product Listing
Create src/ProductList.js a file for showing product list and delete records.
src/ProductList.js
componentDidMount() {
const apiUrl = 'http://localhost/dev/tcxapp/reactapi/products';
fetch(apiUrl)
.then(res => res.json())
.then(
(result) => {
this.setState({
products: result
});
},
(error) => {
this.setState({ error });
}
)
}
deleteProduct(productId) {
const { products } = this.state;
fetch(apiUrl, options)
.then(res => res.json())
.then(
(result) => {
this.setState({
response: result,
products: products.filter(product => product.id !== productId)
});
},
(error) => {
this.setState({ error });
}
)
}
render() {
const { error, products} = this.state;
if(error) {
return (
<div>Error: {error.message}</div>
)
} else {
return(
<div>
<h2>Product List</h2>
{this.state.response.message && <Alert
variant="info">{this.state.response.message}</Alert>}
<Table>
<thead>
<tr>
<th>#ID</th>
<th>Product Name</th>
<th>SKU</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{products.map(product => (
<tr key={product.id}>
<td>{product.id}</td>
<td>{product.product_name}</td>
<td>{product.sku}</td>
<td>{product.price}</td>
<td>
<Button variant="info" onClick={() =>
this.props.editProduct(product.id)}>Edit</Button>
<Button variant="danger" onClick={() =>
this.deleteProduct(product.id)}>Delete</Button>
</td>
</tr>
))}
</tbody>
</Table>
</div>
)
}
}
}
src/AddProduct.js
if(props.product){
this.state = props.product
} else {
this.state = this.initialState;
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
const name = event.target.name;
const value = event.target.value;
this.setState({
[name]: value
})
}
handleSubmit(event) {
event.preventDefault();
this.props.onFormSubmit(this.state);
this.setState(this.initialState);
}
render() {
let pageTitle;
if(this.state.id) {
pageTitle = <h2>Edit Product</h2>
} else {
pageTitle = <h2>Add Product</h2>
}
return(
<div>
{pageTitle}
<Row>
<Col sm={6}>
<Form onSubmit={this.handleSubmit}>
<Form.Group controlId="productName">
<Form.Label>Product Name</Form.Label>
<Form.Control
type="text"
name="productName"
value={this.state.productName}
onChange={this.handleChange}
placeholder="Product Name"/>
</Form.Group>
<Form.Group controlId="sku">
<Form.Label>SKU</Form.Label>
<Form.Control
type="text"
name="sku"
value={this.state.sku}
onChange={this.handleChange}
placeholder="SKU" />
</Form.Group>
<Form.Group controlId="price">
<Form.Label>Price</Form.Label>
<Form.Control
type="text"
name="price"
value={this.state.price}
onChange={this.handleChange}
placeholder="Price" />
</Form.Group>
<Form.Group>
<Form.Control type="hidden" name="id" value={this.state.id}
/>
<Button variant="success" type="submit">Save</Button>
</Form.Group>
</Form>
</Col>
</Row>
</div>
)
}
}
src/App.js
Import AddProduct from ./AddProduct for add and edit product. And also ProductList
component from ./ProductList for showing the proudcts.
import React, { Component } from 'react';
import './App.css';
import { Container, Button, Alert } from 'react-bootstrap';
import ProductList from './ProductList';
import AddProduct from './AddProduct';
onCreate() {
this.setState({ isAddProduct: true });
}
onFormSubmit(data) {
let apiUrl;
if(this.state.isEditProduct){
apiUrl = 'http://localhost/dev/tcxapp/reactapi/editProduct';
} else {
apiUrl = 'http://localhost/dev/tcxapp/reactapi/createProduct';
}
const options = {
method: 'POST',
body: JSON.stringify(data),
myHeaders
};
fetch(apiUrl, options)
.then(res => res.json())
.then(result => {
this.setState({
response: result,
isAddProduct: false,
isEditProduct: false
})
},
(error) => {
this.setState({ error });
}
)
}
const options = {
method: 'POST',
body: formData
}
fetch(apiUrl, options)
.then(res => res.json())
.then(
(result) => {
this.setState({
product: result,
isEditProduct: true,
isAddProduct: true
});
},
(error) => {
this.setState({ error });
}
)
}
render() {
let productForm;
if(this.state.isAddProduct || this.state.isEditProduct) {
productForm = <AddProduct onFormSubmit={this.onFormSubmit}
product={this.state.product} />
}
return (
<div className="App">
<Container>
<h1 style={{textAlign:'center'}}>React Tutorial</h1>
{!this.state.isAddProduct && <Button variant="primary"
onClick={() => this.onCreate()}>Add Product</Button>}
{this.state.response.status === 'success' && <div><br /><Alert
variant="info">{this.state.response.message}</Alert></div>}
{!this.state.isAddProduct && <ProductList
editProduct={this.editProduct}/>}
{ productForm }
{this.state.error && <div>Error:
{this.state.error.message}</div>}
</Container>
</div>
);
}
}
Copy
src/index.js
API
API has created in CodeIgniter. You can learn CodeIgniter 3 Tutorial Step By Step
Controller
application/controllers/ReactApi.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$products = $this->reactapi_model->get_products();
$this->output
->set_content_type('application/json')
->set_output(json_encode($products));
}
$productId = $this->input->post('productId');
$product = $this->reactapi_model->get_product($productId);
$productData = array(
'id' => $product->id,
'productName' => $product->product_name,
'price' => $product->price,
'sku' => $product->sku
);
$this->output
->set_content_type('application/json')
->set_output(json_encode($productData));
}
if( ! empty($formdata)) {
$productName = $formdata['productName'];
$sku = $formdata['sku'];
$price = $formdata['price'];
$productData = array(
'product_name' => $productName,
'price' => $price,
'sku' => $sku,
'is_active' => 1,
'created_at' => date('Y-m-d H:i:s', time())
);
$id = $this->reactapi_model->insert_product($productData);
$response = array(
'status' => 'success',
'message' => 'Product added successfully'
);
}
else {
$response = array(
'status' => 'error'
);
}
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
}
if( ! empty($formdata)) {
$id = $formdata['id'];
$productName = $formdata['productName'];
$sku = $formdata['sku'];
$price = $formdata['price'];
$productData = array(
'product_name' => $productName,
'price' => $price,
'sku' => $sku
);
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
}
$productId = $this->input->post('productId');
$product = $this->reactapi_model->delete_product($productId);
$response = array(
'message' => 'Product deleted successfully.'
);
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
}
}
?>
Copy
Model
application/models/ReactApi_model.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
Conclusion
In this lesson we have learned complete crud operation, how to add, edit, delete and show
product list in React Js using API with the help of an example.