100% found this document useful (1 vote)
698 views10 pages

Crud Operation: Create Insert Delete Update Records in Reactjs

This document discusses how to perform CRUD operations in a React application using an API built with CodeIgniter and MySQL. It includes code examples for creating components to display a product list, add/edit products, and make API calls to fetch, create, update and delete products from the backend database. Components are built to list products, display an add/edit form, and submit data. The API is created using a CodeIgniter controller and model to handle requests and database operations.

Uploaded by

hardiandhella
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
100% found this document useful (1 vote)
698 views10 pages

Crud Operation: Create Insert Delete Update Records in Reactjs

This document discusses how to perform CRUD operations in a React application using an API built with CodeIgniter and MySQL. It includes code examples for creating components to display a product list, add/edit products, and make API calls to fetch, create, update and delete products from the backend database. Components are built to list products, display an add/edit form, and submit data. The API is created using a CodeIgniter controller and model to handle requests and database operations.

Uploaded by

hardiandhella
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 10

CRUD Operation: Create Insert Delete Update records in

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

import React from 'react';


import { Table, Button, Alert } from 'react-bootstrap';

class ProductList extends React.Component {


constructor(props) {
super(props);
this.state = {
error: null,
products: [],
response: {}
}
}

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;

const apiUrl = 'http://localhost/dev/tcxapp/reactapi/deleteProduct';


const formData = new FormData();
formData.append('productId', productId);
const options = {
method: 'POST',
body: formData
}

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>
&nbsp;<Button variant="danger" onClick={() =>
this.deleteProduct(product.id)}>Delete</Button>
</td>
</tr>
))}
</tbody>
</Table>
</div>
)
}
}
}

export default ProductList;


Copy

Add and Edit Product


Create src/AddProduct.js file for add and edit product form and create stateful component
AddProduct.

src/AddProduct.js

import React from 'react';


import { Row, Form, Col, Button } from 'react-bootstrap';

class AddProduct extends React.Component {


constructor(props) {
super(props);
this.initialState = {
id: '',
productName: '',
price: '',
sku: ''
}

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>
)
}
}

export default AddProduct;


Copy

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';

class App extends Component {


constructor(props) {
super(props);
this.state = {
isAddProduct: false,
error: null,
response: {},
product: {},
isEditProduct: false
}
this.onFormSubmit = this.onFormSubmit.bind(this);
}

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 myHeaders = new Headers();


myHeaders.append('Content-Type', 'application/json');

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 });
}
)
}

editProduct = productId => {

const apiUrl = 'http://localhost/dev/tcxapp/reactapi/getProduct';


const formData = new FormData();
formData.append('productId', productId);

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>
);
}
}

export default App;

Copy

src/index.js

import React from 'react';


import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import './index.css';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));


Copy

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');

class ReactApi extends CI_Controller {

public function __construct()


{
parent::__construct();
$this->load->model('reactapi_model');
}

public function products()


{
header("Access-Control-Allow-Origin: *");

$products = $this->reactapi_model->get_products();

$this->output
->set_content_type('application/json')
->set_output(json_encode($products));
}

public function getProduct()


{
header("Access-Control-Allow-Origin: *");

$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));
}

public function createProduct()


{
header("Access-Control-Allow-Origin: *");
header("Access-Control-Request-Headers: GET,POST,OPTIONS,DELETE,PUT");

$formdata = json_decode(file_get_contents('php://input'), true);

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));
}

public function editProduct()


{
header("Access-Control-Allow-Origin: *");
header("Access-Control-Request-Headers: GET,POST,OPTIONS,DELETE,PUT");

$formdata = json_decode(file_get_contents('php://input'), true);

if( ! empty($formdata)) {

$id = $formdata['id'];
$productName = $formdata['productName'];
$sku = $formdata['sku'];
$price = $formdata['price'];

$productData = array(
'product_name' => $productName,
'price' => $price,
'sku' => $sku
);

$id = $this->reactapi_model->update_product($id, $productData);


$response = array(
'status' => 'success',
'message' => 'Product updated successfully.'
);
}
else {
$response = array(
'status' => 'error'
);
}

$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
}

public function deleteProduct()


{
header("Access-Control-Allow-Origin: *");

$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');

class ReactApi_model extends CI_model {

public function get_products()


{
$this->db->where('is_active', 1);
$query = $this->db->get('products');
return $query->result();
}

public function get_product($productId)


{
$this->db->where('is_active', 1);
$this->db->where('id', $productId);
$query = $this->db->get('products');
return $query->row();
}

public function insert_product($productData)


{
$this->db->insert('products', $productData);
return $this->db->insert_id();
}

public function update_product($id, $productData)


{
$this->db->where('id', $id);
$this->db->update('products', $productData);
}

public function delete_product($productId)


{
$this->db->where('id', $productId);
$this->db->delete('products');
}
}
?>
Copy

MySQL Database `products` Table

CREATE TABLE `products` (


`id` int(10) UNSIGNED NOT NULL,
`product_name` varchar(255) CHARACTER SET latin1 DEFAULT NULL,
`sku` varchar(50) CHARACTER SET latin1 DEFAULT NULL,
`price` decimal(8,2) NOT NULL,
`is_active` tinyint(1) NOT NULL,
`created_at` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `products` (`id`, `product_name`, `sku`, `price`, `is_active`,


`created_at`) VALUES
(1, 'Mobile', 'mobile', '6000.00', 1, '2019-02-21 08:46:48'),
(2, 'Laptop', 'laptop', '30000.00', 1, '2019-02-21 08:59:56'),
(3, 'LED Bulb', 'led-bulb', '150.00', 1, '2019-02-21 09:59:56'),
(4, 'TV', 'tv', '20000.00', 1, '2019-02-21 10:59:56'),
(5, 'Mouse', 'mouse', '250.00', 1, '2019-02-21 11:59:56');

ALTER TABLE `products`


ADD PRIMARY KEY (`id`);

ALTER TABLE `products`


MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
COMMIT;
Copy

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.

You might also like