In this post, we are going to discuss how to do a simple CRUD Operation in react js using a bootstrap simple HTML table.

CRUD Meaning

CRUD word that comes from the world of computer programming and directs to the four operations that are considered essential to implement a storage application i.e create, read, update and delete.

Simple React js CRUD Example With Rest API

React JS CRUD example with Rest API

So let’s start React JS CRUD Example — step by step

Step 1

Create react js app using the below command

npx create-react-app crud-app

Step 2

Install bootstrap CSS in our project using the below command

npm install bootstrap –save

Step 3: Rest API for performing Crud operation

1.GET http://restapi.adequateshop.com/api/Tourist

Return list of tourists in the organization, we are going to use this API for binding our table list.

{
  "page": 1,
  "per_page": 10,
  "totalrecord": 8508,
  "total_pages": 851,
  "data": [
    {
      "id": 116597,
      "tourist_name": "Johnyt",
      "tourist_email": "j56644@gmail.com",
      "tourist_profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
      "tourist_location": "Usa",
      "createdat": "2022-05-05T09:32:28.8548478"
    },
    {
      "id": 116595,
      "tourist_name": "Testing",
      "tourist_email": "pppppppp12121@gmail.com",
      "tourist_profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
      "tourist_location": "INDIA",
      "createdat": "2022-05-05T09:28:33.2964054"
    },
    {
      "id": 116592,
      "tourist_name": "John",
      "tourist_email": "joaa44@gmail.com",
      "tourist_profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
      "tourist_location": "Usa",
      "createdat": "2022-05-05T09:09:33.4510789"
    },
    {
      "id": 116589,
      "tourist_name": "John",
      "tourist_email": "johnhj@gmail.com",
      "tourist_profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
      "tourist_location": "Usa",
      "createdat": "2022-05-05T09:03:48.6965879"
    },
    {
      "id": 116588,
      "tourist_name": "John",
      "tourist_email": "jo7898944@gmail.com",
      "tourist_profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
      "tourist_location": "Usa",
      "createdat": "2022-05-05T09:03:24.405684"
    },
    {
      "id": 116584,
      "tourist_name": "Mikelion",
      "tourist_email": "mikepp12388888li88on@gmail.com",
      "tourist_profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
      "tourist_location": "lionParis",
      "createdat": "2022-05-05T08:35:46.0262257"
    },
    {
      "id": 116583,
      "tourist_name": "Mikelion",
      "tourist_email": "mike12388888li88on@gmail.com",
      "tourist_profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
      "tourist_location": "lionParis",
      "createdat": "2022-05-05T08:26:27.837058"
    },
    {
      "id": 116582,
      "tourist_name": "testing12121",
      "tourist_email": "testing121212@gmail.com",
      "tourist_profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
      "tourist_location": "India",
      "createdat": "2022-05-05T08:21:24.4612766"
    },
    {
      "id": 116580,
      "tourist_name": "Mike",
      "tourist_email": "vrushali1212121@gmail.com",
      "tourist_profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
      "tourist_location": "Paris",
      "createdat": "2022-05-05T08:20:33.1709003"
    },
    {
      "id": 116575,
      "tourist_name": "hello",
      "tourist_email": "abcd9839@gmail.com",
      "tourist_profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
      "tourist_location": "Usa",
      "createdat": "2022-05-05T07:30:12.3328337"
    }
  ]
}

2.POST http://restapi.adequateshop.com/api/Tourist

This endpoint is used For making the entry in the database, you need to pass the 3 parameters i.e tourist_nametourist_email, and tourist_location in the request body. 

Request

{
                "tourist_name": "Test user",
                "tourist_email": "testuser123@gmail.com",
                "tourist_location": "USA"
}

API Response

{
                "$id": "1",
                "id": 15863,
                "tourist_name": "Test user",
                "tourist_email": "testuser123@gmail.com",
                "tourist_profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
                "tourist_location": "USA",
                "createdat": "2022-01-03T07:53:37.626145Z"
}

 

3. PUT http://restapi.adequateshop.com/api/Tourist/15863

This endpoint is a PUT endpoint and we use that endpoint for updating the record.

API Request

{
                "id": 15863,
                "tourist_name": "Test Update",
                "tourist_email": "testuser123@gmail.com",
                "tourist_location": "Paris"
}

 

API Response

{
                "$id": "1",
                "id": 15863,
                "tourist_name": "Test Update",
                "tourist_email": "mike123@gmail.com",
                "tourist_profilepicture": "http://restapi.adequateshop.com/Media//images/userimageicon.png",
                "tourist_location": "Paris",
                "createdat": "2022-01-03T07:53:37.626145"
}

4.DELETE  http://restapi.adequateshop.com/api/Tourist/15863

This endpoint is used for deleting the record in the database.

Step 5-Create a “httphelpers” folder inside the src folder in our react js project. and add a file inside that folder with the name “restHelper.js”.

helperclass

Copy and paste the below

restHelper.js

export const restHelper = () => {
    
    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)
            debugger;
            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,
    }
}

I have created the helper class httphelpers/restHelper.jswhich will work as a global helper class and we can utilize that helper in another class or component. using that helper class we will make the different HTTP requests in our application. 

Step 4-Create a “components” folder inside the src folder in our react js project.

Step 4-Right-Click “components” folder ->New File and create the component and I’ll call it Touristtable.js, Crudtourists.js, and Addtourist.js

Components

Touristtable.js

we have created this component, for binding the tourists to the table.

import React from "react"
import Form from "./Addtourist"
import 'bootstrap/dist/css/bootstrap.min.css';

const Touristtable = ({ tourists, postTourist, updateTourist, deleteTourist }) => {
    debugger;
    const showUpdateUser = id => {
        const form = document.getElementsByClassName(`show-form-${id}`)
        form[0].classList.toggle("hide-form")
    }

    const Row = ({ tourist }) => {
        return (
            <>
                <div className='row'>
                    <div className='col-sm-2'>{tourist.tourist_name}</div>
                    <div className='col-sm-3'>{tourist.tourist_email}</div>
                    <div className='col-sm-3'>{tourist.tourist_location}</div>
                    <div className='col-sm-4 buttons'>
                        <button className="btn btn-info"  onClick={() => showUpdateUser(tourist.id)}>Update</button>
                        <button  className="btn btn-danger" onClick={() => deleteTourist(tourist.id)}>delete</button>
                    </div>
                </div>
                <div className={`hide-form show-form-${tourist.id}`}>
                    <Form userData={tourist} postTourist={postTourist} updateTourist={updateTourist} />
                </div>
            </>
        )
    }

    return (
        <div className='table'>
            <div className='row'>
                <div className='col-sm-2'>Name</div>
                <div className='col-sm-3'>Email</div>
                <div className='col-sm-3'>Location</div>
                <div className='col-sm-4'>Actions</div>
            </div>
            <div className='rows'>
                {tourists && tourists.map(u => <Row tourist={u} key={u.id} />)}
            </div>
        </div>
    )
}

export default Touristtable

Crudtourists.js

we have created this component for rendering Touristtable.js component and showing the list to the user.

import React, { useState, useEffect } from "react"
import Form from "./Addtourist"
import Tablelist from "./Touristtable"
import 'bootstrap/dist/css/bootstrap.min.css';

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

const Crudtourists = () => {
    const [tourists, settourists] = useState(null)

    const url = "http://restapi.adequateshop.com/api/Tourist"
    const api = restHelper()

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

    const postTourist = tourist => {
        api
            .postCreate(`${url}`, { body: tourist })
            .then(res => gettourists())
            .catch(err => console.log(err))
    }

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

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

    const gettourists = () => {
        api
            .get(`${url}`)
            .then(res => {
                if(res && res.data)
                {
                    settourists(res.data)
                }
            })
            .catch(err => console.log(err))
    }
    if (!tourists) return null

    return (
        <>
            <h3>New user</h3>
            <Form postUser={postTourist} />
            <div className='container-fluid'>
                <h3>All users</h3>
                <Tablelist
                    tourists={tourists}
                    settourists={settourists}
                    postTourist={postTourist}
                    updateTourist={updateTourist}
                    deleteTourist={deleteTourist}
                />
            </div>
        </>
    )
}

export default Crudtourists

Addtourist.js

we have created this component for adding the tourist information to the database.

import React, { useState } from "react"


const Addtourist = ({ userData = {}, postUser, updateTourist }) => {
    const [user, setUser] = useState({
        id:userData.id ?? 0,
        tourist_name: userData.tourist_name ?? "",
        tourist_email: userData.tourist_email ?? "",
        tourist_location: userData.tourist_location ?? "",
    })

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

    const submitUser = e => {
        e.preventDefault()
        debugger;
        if (user.tourist_name === "" || user.tourist_email === "" || user.tourist_location === "") return

        if (userData.id) {
            debugger;
            updateTourist(userData.id, user)
        } else {
            postUser(user)
        }
        setUser({ ...user, "tourist_name": "","tourist_email": "","tourist_location": "" })
    }

    return (
        <form onSubmit={submitUser} className='form-inline'>
            <div className="form-group">
            <input
                type='text'
                name='tourist_name'
                className="form-control"
                value={user.tourist_name}
                placeholder='Name'
                onChange={e => handleValue(e)}
            />
            </div>
            <div className="form-group">
            <input
                type='email'
                name='tourist_email'
                className="form-control"
                value={user.tourist_email}
                placeholder='Email'
                onChange={e => handleValue(e)}
            />
            </div>
            <div className="form-group">
            <input
                type='text'
                name='tourist_location'
                className="form-control"
                value={user.tourist_location}
                placeholder='location..'
                onChange={e => handleValue(e)}
            />
            </div>
            <input
                className='btn btn-primary btnsubmit'
                type='submit'
                value={`${!userData.id ? "Add new user" : "Save user"}`}
            />
        </form>
    )
}

export default Addtourist

Now open App.js file and import Crudtourists.js

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

export default App;

Now let’s run project using below command

npm start

React JS CRUD Example step by step

I’m assuming that you are familiar with React Js framework and creating React Js applications. If not then please go through the following articles:

The post React Js- Fetch data from API using hooks appeared first on Software Development | Programming Tutorials.



Read More Articles