CRUD Operation In React JS Using Hooks


In this article, I will demonstrate CRUD operations in React JS using Hooks and functional components. I will also illustrate how to implement these operations using the `fetch()` function with a REST API. Additionally, I'll cover how to create functionality for inserting, updating, and deleting data in React JS. We'll enhance the user interface by utilizing Bootstrap and Font Awesome to create an aesthetically pleasing UI for our application.

In this We will discuses below point

  • CRUD operation in React using functional component
  • CRUD operation in React JS using Hooks

We can see in the below image that here we have created both HTML tables with delete and edit icons and options for adding a new customer.

CRUD operation in React JS using Hooks with api

OnClick of edit icon It will show a new row from where you can update the customer detail. 

For performing the operation, we need to create a REST that will participate in CRUD operations , we are going to use the below customer API. we are going to create a simple customer page in which we will perform CRUD (Create, Read, Update and Delete) Operation using the below rest API. 

1.GET http://samplerestapi.com/api/Customer

Response:

[
  {
"id": 121743,
"name": "dhiraj",
"email": "[email protected]",
"location": "IND"
  },
  {
"id": 121742,
"name": "anjoo",
"email": "[email protected]",
"location": "pune"
  },
  {
"id": 121741,
"name": "Mike",
"email": "[email protected]",
"location": "Paris"
  },
  {
"id": 121740,
"name": "Adil",
"email": "[email protected]",
"location": "Lahore"
  },
  {
"id": 121739,
"name": "dhiraj",
"email": "[email protected]",
"location": "IND"
  },
  {
"id": 121738,
"name": "snehal",
"email": "[email protected]",
"location": "sjhadjdwq"
  },
  {
"id": 121737,
"name": "dhiraj",
"email": "[email protected]",
"location": "Inda"
  },
  {
"id": 121736,
"name": "dhiraj",
"email": "[email protected]",
"location": "Inda"
  },
  {
"id": 121722,
"name": "guru",
"email": "[email protected]",
"location": "tirupati"
  },
  {
"id": 121661,
"name": "sdasdw",
"email": "asdadw",
"location": "qdsadwq"
  },
  {
"id": 121660,
"name": "Mike",
"email": "[email protected]",
"location": "Paris"
  },
  {
"id": 121659,
"name": "qdsadsa",
"email": "wdqdsad",
"location": "wqdsadwq"
  },
  {
"id": 121658,
"name": "sq",
"email": "sqqwdq",
"location": "dwqdq"
  },
  {
"id": 121657,
"name": "dwdwq",
"email": "dwqdsad",
"location": "dsqwqdwq"
  },
  {
"id": 121656,
"name": "ascas",
"email": "sadwqdsa",
"location": "dwqdsa"
  },
  {
"id": 121655,
"name": "abcabcsjk",
"email": "cbsajkbcsjk",
"location": "cbsajkcbsa"
  },
  {
"id": 121654,
"name": "acbcsbaj",
"email": "sbahjbscaj",
"location": "csbhjcsab"
  },
  {
"id": 121652,
"name": "qweqwe",
"email": "qweqwe",
"location": "dwqdwqsd"
  },
  {
"id": 121651,
"name": "asd",
"email": "asdhwudhu",
"location": "sjhadjdwq"
  },
  {
"id": 121650,
"name": "Dandy",
"email": "dandy2@fhu",
"location": "dsjdiwq"
  }
]

2.POST http://samplerestapi.com/api/Customer

Request Parameter

{ 
"name": "string",
"email": "string",
"location": "string"
}

3. PUT http://samplerestapi.com/api/Customer/15624
Request Parameter

{
"id": 15624,
"name": "string",
"email": "string",
"location": "string"
}

4.DELETE  http://samplerestapi.com/api/Customer/15624
Step 1. CREATE NEW React js PROJECT 

To create a new project, Open the terminal and run the below command.

npx create-react-app crud-app

Step 2. Install bootstrap CSS and font-awesome in our application using the below command for making beautiful UI.

npm install bootstrap –save

npm install –save font-awesome

Step 3. Create React Component in your project

Create a “components” folder inside the src folder in our react js application and add 3 files inside that folder.

  • UserAction.js
  • CreateCustomer.js
  • CustomerList.js

CRUD operation in React JS using Hooks

Step 4. Create a Helper class file for calling API 

Create a “httphelpers” folder inside the src folder in our react js application and restAPIHelper.js file inside that folder.

Paste the below code inside that folder

restAPIHelper.js

export const restAPIHelper = () => {
    
const callAPI = async (endpointurl, options = {}) => {
const defaultHTTPMethod = "GET"
const defaultHTTPHeaders = {  //set defaultHeaders of Http request
"Content-Type": "application/json",
            Accept: "application/json",
        }
const controller = new AbortController() //using  AbortController to cancel ongoing fetch requests
        options.signal = controller.signal

        options.method = options.method || defaultHTTPMethod

        options.headers = options.headers
            ? { ...defaultHTTPHeaders, ...options.headers }
            : defaultHTTPHeaders

        options.body = JSON.stringify(options.body) || false
if (!options.body) delete options.body

        setTimeout(() => { // cancel request if it will take more then 5s 
            controller.abort()
        }, 5000)

try {
const apiResponse = await fetch(endpointurl, options)
return await apiResponse.json()
        } catch (err) {
return err
        }
    }

//calling get API For fetching data
const get = (endpointurl, options = {}) => callAPI(endpointurl, options)

//Post to insert 
const postCreate = (endpointurl, options) => {
        options.method = "POST"
return callAPI(endpointurl, options)
    }


//Put Api calling
const putUpdate = (endpointurl, options) => {
        options.method = "PUT"
return callAPI(endpointurl, options)
    }

//Delete Api calling
const deletedata = (endpointurl, options) => {
        options.method = "DELETE"
return callAPI(endpointurl, options)
    }

return {
get,
        postCreate,
        putUpdate,
        deletedata,
    }
}

Step 5. Write coding in the file to perform crud operation

UserAction.js

import React, { useState, useEffect } from "react"
import CreateAgent from "./CreateCustomer"
import UserList from "./CustomerList"
import 'bootstrap/dist/css/bootstrap.min.css';

import { restAPIHelper } from "../httphelpers/restAPIHelper"

const UserAction = () => {
const [customers, setcustomers] = useState(null)

const url = "http://samplerestapi.com/api/Customer"
const api = restAPIHelper()

    useEffect(() => {
        getCustomers()
    }, [])

const postCustomer = customer => {
        api
            .postCreate(`${url}`, { body: customer })
            .then(res => getCustomers())
            .catch(err => console.log(err))
    }

const updateCustomer = (id, customer) => {
        api
            .putUpdate(`${url}/${id}`, { body: customer })
            .then(res => getCustomers())
            .catch(err => console.log(err))
    }

const deleteCustomer = id => {
        api
            .deletedata(`${url}/${id}`, {})
            .then(res => getCustomers())
            .catch(err => console.log(err))
    }

const getCustomers = () => {
        api
            .get(`${url}`)
            .then(res => {
if(res)
                {
                    setcustomers(res)
                }
            })
            .catch(err => console.log(err))
    }
if (!customers) return null

return (
        <>
            <h3>Add New Record</h3>
            <table>
                <tbody>
                    <tr>
                    <CreateAgent postCustomer={postCustomer} />
                    </tr>
                </tbody>
            </table>
            
            <div className='container-fluid'>
                <h3>All Tourist</h3>
                <UserList
                    customers={customers}
                    setcustomers={setcustomers}
                    postCustomer={postCustomer}
                    updateCustomer={updateCustomer}
                    deleteCustomer={deleteCustomer}
                />
            </div>
        </>
    )
}

export default UserAction

CustomerList.js

import React from "react"
import CreateCustomer from "./CreateCustomer"
import 'bootstrap/dist/css/bootstrap.min.css';
import 'font-awesome/css/font-awesome.min.css';

const CustomerList = ({ customers, postCustomer, updateCustomer, deleteCustomer }) => {
const showHideUpdateRow = id => {
const form = document.getElementsByClassName(`show-form-${id}`)
        form[0].classList.toggle("hide-form")
    }

const Row = ({ customer }) => {
return (
            <>
                <tr>
                    <td>{customer.name}</td>
                    <td>{customer.email}</td>
                    <td>{customer.location}</td>
                    <td>
                        <i className="fa fa-pencil-square fa-2x text-info" onClick={() => showHideUpdateRow(customer.id)}></i>
                        <i className="fa fa-trash fa-2x text-danger" onClick={() => deleteCustomer(customer.id)}></i>    
                    </td>
                </tr>
                <tr className={`hide-form show-form-${customer.id}`}> 
                   <CreateCustomer userData={customer} postCustomer={postCustomer} updateCustomer={updateCustomer} showHideUpdateRow={showHideUpdateRow} />
                </tr>
            </>
        )
    }

return (
        
            <table className="table">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Location</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                            {customers && customers.map(u => <Row customer={u} key={u.id} />)}
                   </tbody>
            </table>
        
    )
}

export default CustomerList

CreateCustomer.js

import React, { useState } from "react"
import 'font-awesome/css/font-awesome.min.css';
import { faL } from "@fortawesome/free-solid-svg-icons";


const CreateCustomer= ({ userData = {}, postCustomer, updateCustomer,showHideUpdateRow }) => {
const [user, setUser] = useState({
        id: userData.id ?? 0,
        name: userData.name ?? "",
        email: userData.email ?? "",
        location: userData.location ?? "",
    })

const handleValue = e => {
        setUser({ ...user, [e.target.name]: e.target.value })
    }

const submitUser = e => {
        e.preventDefault()
        debugger;
if (user.name === "" || user.email === "" || user.location === "") return

if (userData.id) {
            debugger;
            updateCustomer(userData.id, user)
        } else {
            postCustomer(user)
        }
        setUser({ ...user, "name": "", "email": "", "location": "" })
    }
const hiderow = e => {
        showHideUpdateRow(userData.id);
    }
const isAdd = !userData.id ? true : false;
return (
        <>
            <td>
                <input
                    type='text'
                    name='name'
                    className="form-control"
                    value={user.name}
                    placeholder='Name'
                    onChange={e => handleValue(e)}
                />
            </td>
            <td>
                <input
                    type='email'
                    name='email'
                    className="form-control"
                    value={user.email}
                    placeholder='Email'
                    onChange={e => handleValue(e)}
                />
            </td>
            <td>
                <input
                    type='text'
                    name='location'
                    className="form-control"
                    value={user.location}
                    placeholder='location..'
                    onChange={e => handleValue(e)}
                />
            </td>
            <td>
                {isAdd ?
                    <input
                        className='btn btn-primary btnsubmit'
                        type='submit'
                        value={`${!userData.id ? "Add new user" : "Save user"}`}
                        onClick={submitUser}
                    /> :
                    <i className="fa fa-check fa-2x text-success" onClick={submitUser}></i>
                }
                {isAdd ? "" : <i className="fa fa-times fa-2x text-muted" onClick={hiderow}></i>}
            </td>
        </>
    )
}

export default CreateCustomer

Step 6. Import UserAction.js component in App.js

App.js

import logo from './logo.svg';
import './App.css';
import UserAction from "./components/UserAction"
import 'bootstrap/dist/css/bootstrap.min.css';
function App() {
return (
    <div className="container-fluid">
      <main>
                <UserAction />
            </main>
    </div>
  );
}

export default App;

so, everything is done now run npm start command to see the result and perform crud operation.

CRUD operation in React JS using Hooks with api

Respond is a front-end library that is answerable for the UI. It is neither an entire system nor a language. It is an open-source JavaScript library for building the UI (UI) of an application.Respond is explanatory, adaptable, and simple to learn. Respond is kept up with by Facebook and a local area of individual engineers. At present, there is an enormous interest in React.js in the business.

Respond can be utilized for the advancement of single-page applications or versatile applications. For complex applications, React involves extra libraries for state the board, steering, and cooperation with an API.

Respond permits us to form complex UIs by composing a little piece of code. A secluded piece of code is called Component.

Essentials of React

You ought to know about HTML, CSS, and JavaScript essentials.You ought to likewise know about ES6.