30 September 2016

CRUD Operation Example in ReactJS or React.js

Hi Friends,

In this post I am going to show you how you can perform DML operation on database using ReactJS.

For instance let's take an example of Departments table in HR schema of Oracle XE database. As we have discussed about the about the create functionality in my previous post on below link so we will see how we can add the update and delete functionality of CRUD operation.

These all operation will happen through Rest services which is build based on Departments table.
Let's say I have a restful webservice built on database table named "Departments" in HR Schema of Oracle XE database. This restful service will perform the create/update/delete in Departments table. This restful service accepts the JSON data as the input and do the operation on database table whatever operation we will call.


We are showing all the records available in the Departments table using ajax call and rendering with help of ReactJS which you can see in the below post :

http://www.code4fusion.com/2016/09/column-level-filter-in-fixed-data-table.html

For create operation example you can follow the below link :

http://www.code4fusion.com/2016/09/create-operation-on-database-table.html

To perform update and delete we need to select the row of the table. So for the selection of row you need to add onRowClick={this.rowClicked} property in your fixed data table as shown below:

 <Table
      filterable={['id', 'departmentId', 'departmentName']}
      noDataText="No matching records found"
      height={h}
      width={600}
      rowsCount={rows.length}
      rowHeight={30}
      headerHeight={80}
      onRowClick={this.rowClicked}
      rowGetter={function(rowIndex) {return rows[rowIndex]; }}>
      <Column dataKey="id" width={200} height={50} label="Serial Number" headerRenderer={this.renderHeader}/>
      <Column dataKey="departmentId" width={200} label="Department Id" headerRenderer={this.renderHeader}/>
      <Column dataKey="departmentName" width={200} label="Department Name" headerRenderer={this.renderHeader}/>
    </Table>


and following lines of code we need to write to get the index and other value from the row inside  rowClicked function. 

rowClicked : function(e, index){
var deptArr=this.state.departments;
var depId=deptArr[index].departmentId;
var depName=deptArr[index].departmentName;
this.setState({id:index, deptIdValue: depId, deptNameValue:depName});
}


and then we need to modify our input text to get the value whatever selected in the table.

<input name="departmentId" ref="departmentId" type="text" id="departmentId" placeholder="Department Id" value={this.state.deptIdValue} onChange={this.onChangeDeptId}/><br/><br/>
       <input name="departmentName" ref="departmentName" type="text" id="departmentName" placeholder="Department Name" value={this.state.deptNameValue} onChange={this.onChangeDeptName}/><br/><br/>


 Now we have written the two method two handle the update in the Department Id and Department Name input text fields.

 onChangeDeptId : function(event){
this.setState({deptIdValue: event.target.value});
},
onChangeDeptName : function(event){
this.setState({deptNameValue: event.target.value});
}


Now we need to add two more button for Update and Delete in out component which you can do it by writing below code in your component.

<input name="Update" value="Update" type="Submit" onClick = {this.updateDepartment}/>
<input name="Delete" value="Delete" type="Submit" onClick = {this.deleteDepartment}/>


After this to add the update and delete functionality we have added two methods which are as follows in our react component.

updateDepartment : function(event){
var id = this.state.id;
var deptId=this.state.deptIdValue;
var deptName=this.state.deptNameValue;
this.state.departments.splice(id, 1, {
                         "id":id+1,
                         "departmentId": deptId,
                         "departmentName": deptName
                      });
this.setState({departments: this.state.departments});
this.setState({departments1: this.state.departments});                     
 var deptUp =      {"departmentId": deptId,"departmentName" :deptName};                     
                $.ajax({
                 type: "PUT",
                 url: this.props.dataUrl+deptId,
                 data: JSON.stringify(deptUp),
                 contentType: "application/json; charset=utf-8",
                 dataType: "json",
                 processData: true,
                 success: function (data, status, jqXHR) {
                 alert("Row Updated successfully.");
                 },
                 error: function (xhr) {
                     alert(xhr.responseText);
                 }
             });                 
                     
},
deleteDepartment : function(event){
var id = this.state.id;
var deptId=this.state.deptIdValue;
$.ajax({
                 type: "DELETE",
                 url: this.props.dataUrl+deptId,
                 processData: true,
                 success: function (data, status, jqXHR) {
                 alert("Row Deleted successfully.");
                 },
                 error: function (xhr) {
                     alert(xhr.responseText);
                 }
             });
this.state.departments.splice(id, 1);   
this.setState({departments: this.state.departments});
this.setState({departments1: this.state.departments});       

},


Now after adding this if you run you page then you can see the screen like below:




















once you select any row then the rows value will be populated for update or delete as shown below:


Now if you update the value in input text and click on "Update" button then the value will be updated in UI table as well as database table and you will get a confirmation message "Row Updated successfully".

 Now let check in Database whether the value got updated or not.


















Now you can see that the value in database also got updated.

Now lets test the delete functionality by selecting other row and try to delete.



















Now when we will delete the record we will get the confirmation message as "Row Deleted Successfully" as shown below.




















And then you can see that the ro is deleted from UI table.

Now let's check whether the row is deleted from database table or not.





















So here we can see that the record is deleted from the database table as well.

For this example you complete jsx code should look like this:

import React from "react";
import ReactDOM from "react-dom";
import {Table, Column, Cell} from 'fixed-data-table';

var divStyleLeft = {
 width: '50%', float:'left'
};

var divStyleRight= {
 width: '50%', float:'right'
};


var DepartmentGridTable = React.createClass({
 getInitialState: function() {
    return {departments: [],  departments1:[], rows:[], deptIdValue: '', deptNameValue: '', id:''};
  },
    
 renderHeader(label, cellDataKey) {
  return <div>
        <span>{label}</span>
          <div>
            <br />
            <input type="text" onChange={this.onFilterChange.bind(this, cellDataKey)}/>
          </div>
      </div>;
},

onFilterChange(cellDataKey, event) {
  if (!event.target.value) {
    this.setState({
      departments: this.state.departments1,
    });
  }
  var filterBy = event.target.value.toString().toLowerCase();
  var size = this.state.departments1.length;
  var filteredList = [];
  for (var index = 0; index < size; index++) {
    var v = this.state.departments1[index][cellDataKey];
    if (v.toString().toLowerCase().indexOf(filterBy) !== -1) {
      filteredList.push(this.state.departments1[index]);
    }
  }
  this.setState({
    departments: filteredList,
  });
},
addDepartment: function(event) {   
   var lastIndex = this.state.departments.length;
   var dept = {"departmentId": this.refs.departmentId.value,"departmentName" :this.refs.departmentName.value};
   var deptVirtual = {"id": lastIndex+1, "departmentId": this.refs.departmentId.value,"departmentName" :this.refs.departmentName.value};
   this.setState({departments:this.state.departments.concat([deptVirtual])});
   console.log(this.state.departments);
        $.ajax({
                 type: "POST",
                 url: this.props.dataUrl+"add",
                 data: JSON.stringify(dept),
                 contentType: "application/json; charset=utf-8",
                 dataType: "json",
                 processData: true,
                 success: function (data, status, jqXHR) {
               
                 alert("New department added successfully");
                 },
                 error: function (xhr) {
                     alert(xhr.responseText);
                 }
             });     
  },
rowClicked : function(e, index){
var deptArr=this.state.departments;
var depId=deptArr[index].departmentId;
var depName=deptArr[index].departmentName;
this.setState({id:index, deptIdValue: depId, deptNameValue:depName});
},
onChangeDeptId : function(event){
this.setState({deptIdValue: event.target.value});
},
onChangeDeptName : function(event){
this.setState({deptNameValue: event.target.value});
},
updateDepartment : function(event){
var id = this.state.id;
var deptId=this.state.deptIdValue;
var deptName=this.state.deptNameValue;
this.state.departments.splice(id, 1, {
                         "id":id+1,
                         "departmentId": deptId,
                         "departmentName": deptName
                      });
this.setState({departments: this.state.departments});
this.setState({departments1: this.state.departments});                     
 var deptUp =      {"departmentId": deptId,"departmentName" :deptName};                     
                $.ajax({
                 type: "PUT",
                 url: this.props.dataUrl+deptId,
                 data: JSON.stringify(deptUp),
                 contentType: "application/json; charset=utf-8",
                 dataType: "json",
                 processData: true,
                 success: function (data, status, jqXHR) {
                 alert("Row Updated successfully.");
                 },
                 error: function (xhr) {
                     alert(xhr.responseText);
                 }
             });                 
                     
},
deleteDepartment : function(event){
var id = this.state.id;
var deptId=this.state.deptIdValue;
$.ajax({
                 type: "DELETE",
                 url: this.props.dataUrl+deptId,
                 processData: true,
                 success: function (data, status, jqXHR) {
                 alert("Row Deleted successfully.");
                 },
                 error: function (xhr) {
                     alert(xhr.responseText);
                 }
             });
this.state.departments.splice(id, 1);   
this.setState({departments: this.state.departments});
this.setState({departments1: this.state.departments});       

},
componentDidMount: function() {
     $.ajax({
      url: this.props.dataUrl,
      dataType: 'json',
      success: function(data) {
     
      var deptArray=[];

var arrayLength = data.length;
for (var i = 0; i < arrayLength; i++) {
deptArray.push(
{                     
                        "id" : i+1,
                        departmentId: data[i].departmentId,
                        departmentName:  data[i].departmentName
                    });

}
         this.setState({departments: deptArray});
         this.setState({departments1: deptArray});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.dataUrl, status, err.toString());
      }.bind(this)
    });
  },
 render: function(){
 var rows = this.state.departments;
 var h= rows.length*30+85;
    return (
    <div>
    <div  style={divStyleRight}>
  <h1> Enter Department </h1>
       <input name="departmentId" ref="departmentId" type="text" id="departmentId" placeholder="Department Id" value={this.state.deptIdValue} onChange={this.onChangeDeptId}/><br/><br/>
       <input name="departmentName" ref="departmentName" type="text" id="departmentName" placeholder="Department Name" value={this.state.deptNameValue} onChange={this.onChangeDeptName}/><br/><br/>
       <input name="Submit" value="Submit" type="Submit" onClick = {this.addDepartment}/>
       <input name="Update" value="Update" type="Submit" onClick = {this.updateDepartment}/>
       <input name="Delete" value="Delete" type="Submit" onClick = {this.deleteDepartment}/>
</div>
    <div  style={divStyleLeft}>
    <Table
      filterable={['id', 'departmentId', 'departmentName']}
      noDataText="No matching records found"
      height={h}
      width={600}
      rowsCount={rows.length}
      rowHeight={30}
      headerHeight={80}
      onRowClick={this.rowClicked}
      rowGetter={function(rowIndex) {return rows[rowIndex]; }}>
      <Column dataKey="id" width={200} height={50} label="Serial Number" headerRenderer={this.renderHeader}/>
      <Column dataKey="departmentId" width={200} label="Department Id" headerRenderer={this.renderHeader}/>
      <Column dataKey="departmentName" width={200} label="Department Name" headerRenderer={this.renderHeader}/>
    </Table>
    </div>
    </div>);
     }

 });

ReactDOM.render(
 <DepartmentGridTable dataUrl ="http://localhost:9001/TestRestEasy/rest/departments/"/>,
  document.querySelector("#container")
);


And the code for your html file should look like this:

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-2.2.0.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react-dom.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/fixed-data-table/0.6.3/fixed-data-table.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/fixed-data-table/0.6.3/fixed-data-table.min.css"></script>
 <link href="https://cdnjs.cloudflare.com/ajax/libs/fixed-data-table/0.6.3/fixed-data-table.css" rel="stylesheet">
</head>
<body>
  <div id="container"></div>
  <script src="output/myCode.js"></script>
</body>
</html>


That is all about CRUD Operation in ReactJS.

Happy Coding :)

0 on: "CRUD Operation Example in ReactJS or React.js"