Pages

How to create a CRUD operation in ReactJS

 Create a folder and open the command line prompt. Enter the following command to create an app. Make sure, you have already installed NodeJS.


npx create-react-app Your_App_Name


It will take some time to install the required dependencies.


In this tutorial, we will learn about CRUD operations. First, we will start with the creation operation.

Also, we will learn about routes. So, let's start with the create operation.


Create operation


Go to bootstrap, and copy the CSS, and add it to the index.html in the header.


<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">



We can also select the form from Bootstrap and add it to the code.


Now, take a look at the code. The following code is to create the table in the register page.


 <h2>Register</h2>

    <form>

          <div className="mb-3">

              <label htmlFor="exampleInputEmail1" className="form-label">Full Name</label>

              <input type="text" className="form-control" onChange={(e)=>setName(e.target.value)} />

          </div>

          <div className="mb-3">

              <label htmlFor="exampleInputEmail1" className="form-label">Email address</label>

              <input type="email" className="form-control" onChange={(e)=>setEmail(e.target.value)} />

          </div>

          <div className="mb-3">

              <label htmlFor="exampleInputPassword1" className="form-label">Password</label>

              <input type="password" className="form-control" onChange={(e)=>setPassword(e.target.value)}/>

          </div>

          <button type="submit" className="btn btn-primary" onClick={handleSubmit}>Submit</button>

          <div><p>Already, have an account<Link to="/login" > Login </Link> </p></div>

      </form>


When a user enters the details in form, we use “useState” to store the data.


    const [name, setName] = useState("");

    const [email, setEmail] = useState("");

    const [password, setPassword] = useState("");


We will make an onChange function in <input/> and pass the setName, setEmail and setPassword. S0, whatever we pass the data in the function will store in useState. The data will be stored in name, email and password.



In the input field, the value entered by the user will be set  in setName, setEmail, and setPassword. Whatever we pass from the functions setName, setEmail, and setPassword will be saved as name, email, and password in useState.



Now, to submit the form, we will make a function on the submit button. Take a “onClick” function.


Read this function, and also, we will write the logic here. We will use “axios” to post the data. It accepts some parameters like url, method, header, and data.


To use the “axios”, first we have to install its library using the command -


npm install axios


We are registering, so we will use the post method, we have added a post url, and we will also accept some data and store it in the object form.


 const history = useNavigate();

    const handleSubmit = (e)=>{

        e.preventDefault();

        axios.post(

            'https://localhost:44395/api/Customer/RegisterCustomer',

            {name:name , email: email , password:password,header}

           

        )       

    };

 

Here, we have the full code.


import React , {useState} from 'react'

import { useNavigate } from 'react-router-dom';

import axios from 'axios';

import { Link } from 'react-router-dom';


const Register = () => {

    const [name, setName] = useState("");

    const [email, setEmail] = useState("");

    const [password, setPassword] = useState("");


    const history = useNavigate();

    const handleSubmit = (e)=>{

        e.preventDefault();

        axios.post(

            'https://localhost:44395/api/Customer/RegisterCustomer',

            {name:name , email: email , password:password,header}

           

        )

    };

  return (

    <>

    <h2>Register</h2>

    <form>

          <div className="mb-3">

              <label htmlFor="exampleInputEmail1" className="form-label">Full Name</label>

              <input type="text" className="form-control" onChange={(e)=>setName(e.target.value)} />

          </div>

          <div className="mb-3">

              <label htmlFor="exampleInputEmail1" className="form-label">Email address</label>

              <input type="email" className="form-control" onChange={(e)=>setEmail(e.target.value)} />

          </div>

          <div className="mb-3">

              <label htmlFor="exampleInputPassword1" className="form-label">Password</label>

              <input type="password" className="form-control" onChange={(e)=>setPassword(e.target.value)}/>

          </div>

          <button type="submit" className="btn btn-primary" onClick={handleSubmit}>Submit</button>

          <div><p>Already, have an account<Link to="/login" > Login </Link> </p></div>

      </form>

      </>

  )

}


export default Register


Before going to the login page, we will take a look at routes. Go to the App.js file and provide the route for every page to render to that page.


<div className="container">

      <BrowserRouter>

      <Routes>

      <Route exact path="/" element={<Register />}></Route>

      <Route exact path="/login" element={<Login />}></Route>

      <Route exact path="/dashboard" element={<Dashboard />}></Route>

      <Route exact path="/update" element={<Update />}></Route>

      </Routes>

      </BrowserRouter>

    </div>


Here, we are also creating one login form which is also a Create operation


Here is the full code


import React, { useState } from "react";

import { useNavigate } from "react-router-dom";

import axios from "axios";


const Login = () => {

  const [email, setEmail] = useState("");

  const [password, setPassword] = useState("");


  const history = useNavigate();

  const handleSubmit = (e) => {

    e.preventDefault();

    axios

      .post("https://localhost:44395/api/Customer/LoginCustomer", {

        email: email,

        password: password,

      })

      .then((res) => {

        console.log("my res", res);

        if (res.data.code === 200) {

          history("/dashboard");

        } else {

          history("/login");

        }

      });

  };


  return (

    <>

    <h2>Login</h2>

    <form>

      <div className="mb-3">

        <label htmlFor="exampleInputEmail1" className="form-label">

          Email address

        </label>

        <input

          type="email"

          className="form-control"

          onChange={(e) => setEmail(e.target.value)}

        />

      </div>

      <div className="mb-3">

        <label htmlFor="exampleInputPassword1" className="form-label">

          Password

        </label>

        <input

          type="password"

          className="form-control"

          onChange={(e) => setPassword(e.target.value)}

        />

      </div>

      <button type="submit" className="btn btn-primary" onClick={handleSubmit}>

        Login

      </button>

    </form>

    </>

  );

};


export default Login;



Read operation


Add the following code to the Dashboard..js file


To display the data, we will use “Get” url.


First, create a function and under the function use “axios”. We will take the “Get” method and place a get url. 


The following line will return a promise -


axios.get("https://localhost:44395/api/Customer/TblCustomer")


And to handle the promise, we use “.then”. To store the data, we use “useState”. 


const [data, setData] = useState([]);


We set the data to store the data in “data”.


setData(res.data);


Whenever the page gets reloaded and the value changes, everytime function getData() will be called.


Then only we can see data. For this, we take help of “useEffect”.


useEffect in react is basically a hook that run whenever useState is run or the value changes.


useEffect(()=>{

    getData();

},[]);


Inside useEffect, call the getData() function to call everytime and to display the data.


To delete, we will take a delete function and will pass the id on clicking delete button.

We will go for explanation in delete operation.

<td><button className='btn-danger' onClick={()=>handleDelete(eachData.id)}>Delete </button></td>


To edit, on clicking on Edit button, onClick function will be call where we can update the data. We will explain later in the update operation.

<button className='btn-success' onClick={() => setToLocalStorage(eachData.id,eachData.name,eachData.email)}>Edit</button>


Here is the full code of Read operation.


import React from 'react'

import { Link } from 'react-router-dom';

import { useState, useEffect } from 'react';

import axios from 'axios';


const Dashboard = () => {


  const [data, setData] = useState([]);


  function getData() {

      axios.get("https://localhost:44395/api/Customer/TblCustomer")

      .then((res) => {

          console.log(res.data);

          setData(res.data);

      });

  }


  function handleDelete(id)

  {

     

   axios.delete(`https://localhost:44395/api/Customer/DeleteCustomer/${id}`)

      .then(()=>{

      getData()

                })

  }


  const setToLocalStorage = (id,name,email,password) => {

    localStorage.setItem("id",id);

    localStorage.setItem("name",name);

    localStorage.setItem("email",email);

    localStorage.setItem("password",password);

}


  useEffect(()=>{

    getData();

},[]);


  return (

    <>

    <h2>Dashboard</h2>

    <table class="table">

  <thead>

    <tr>

      <th scope="col">Sn</th>

      <th scope="col">Name</th>

      <th scope="col">Email</th>

      <th scope="col">Edit</th>

      <th scope="col">Delete</th>

    </tr>

  </thead>

  { data.map((eachData,i)=> {

    return(

        <>

        <tbody>

    <tr>

     

      <th scope="row">{i+ 1}</th>

      <td>{eachData.name}</td>

      <td>{eachData.email}</td>

      <td>

        <Link to= "/update">

            <button className='btn-success' onClick={() => setToLocalStorage(eachData.id,eachData.name,eachData.email,eachData.password)}>Edit</button>

        </Link>

      </td>

      <td><button className='btn-danger' onClick={()=>handleDelete(eachData.id)}>Delete </button></td>

    </tr>

   

   </tbody>

        </>

    )

  })

}

</table>

</>

  )

}


export default Dashboard




Update Operation


First, consider on the read operation page.

We will take a onClick function on the Edit button to navigate on the edit page.



<button className='btn-success' onClick={() => setToLocalStorage(eachData.id,eachData.name,eachData.email,eachData.password)}>Edit</button>


When we click on the edit button, the database will be stored in the local storage.

On onClick , we are calling a function setLocalStorage() and will pass a parameter

named id, name , email and password.

Now, we define the function at the top.


  const setToLocalStorage = (id,name,email,password) => {

    localStorage.setItem("id",id);

    localStorage.setItem("name",name);

    localStorage.setItem("email",email);

    localStorage.setItem("password",password);

}


We read the data id, name, email and password and took the local storage to store the key and value. 


 When data is stored in local storage, then we will read it on the update page.

 Now, on the update page, we will use useState to read and store the data.


    const[id,setId] = useState(0);

    const[name,setName] = useState("");

    const[email,setEmail] = useState("");

    const[password,setPassword] = useState("");


Now, we will use useEffect to display the data.

    useEffect(()=>{

        setId(localStorage.getItem("id"));

        setName(localStorage.getItem("name"));

        setEmail(localStorage.getItem("email"));

        setPassword(localStorage.getItem("password"));

    },[]);


First it will get the id,name, email and password and then it will set it.

To show the data on the update form we will take the value in the input field.


Now, we take an update button to update the data given on the field. Take an onClick function.


  <button type="submit" className="btn btn-primary"

   onClick={handleUpdate}

  > Update

    </button>


At the top, we will define a function name handleUpdate(). To update, we use “Put” method with “axios”. After hitting the “put” url, we are calling “.then” to navigate it to the dashboard page.


    const handleUpdate = (e) => {

        e.preventDefault();

        console.log("Id",id);

        axios.put(`https://localhost:44395/api/Customer/UpdateCus`,

        {

            id:id,

            name:name,

            email:email,

            password: password,

        }

        ).then(()=>{

            navigate("/dashboard");

        });

    };


Here the complete code of Update operation


import axios from 'axios';

import React, { useEffect, useState } from 'react'

import { useNavigate } from 'react-router-dom';


const Update = () => {


    const[id,setId] = useState(0);

    const[name,setName] = useState("");

    const[email,setEmail] = useState("");

    const[password,setPassword] = useState("");


    const navigate = useNavigate();


    useEffect(()=>{

        setId(localStorage.getItem("id"));

        setName(localStorage.getItem("name"));

        setEmail(localStorage.getItem("email"));

        setPassword(localStorage.getItem("password"));

    },[]);


    const handleUpdate = (e) => {

        e.preventDefault();

        console.log("Id",id);

        axios.put(`https://localhost:44395/api/Customer/UpdateCus`,

        {

            id:id,

            name:name,

            email:email,

            password: password,

        }

        ).then(()=>{

            navigate("/dashboard");

        });

    };


  return (

    <>

    <h2>Update</h2>

  <form>

  <div className="mb-3">

    <label className="form-label">Name</label>

    <input type="text" className="form-control"

    value={name}

     onChange={(e)=>setName(e.target.value)}

    />

  </div>


  <div className="mb-3">

    <label className="form-label">Email address</label>

    <input type="email" className="form-control"

    value={email}

     onChange={(e)=>setEmail(e.target.value)}

    />

  </div>


  <div className="mb-3">

    <label className="form-label">Password</label>

    <input type="password" className="form-control"  value={password}

     onChange={(e)=>setPassword(e.target.value)} />

          </div>


  <button type="submit" className="btn btn-primary"

   onClick={handleUpdate}

  > Update

    </button>

</form>

    </>

  )

}


export default Update


Delete operation

We will take one delete function, let’s say onClick function on delete button.


We will pass “id”, to delete that data.


<td><button className='btn-danger' onClick={()=>handleDelete(eachData.id)}>Delete </button></td>


Now, we will define handle delete. So, make it function at the top.


function handleDelete(id)

  { axios.delete(`https://localhost:44395/api/Customer/DeleteCustomer/${id}`)

      .then(()=>{

      getData()

                })

  }


We will read “id” as a parameter. So, whenever we click on the delete button, every time delete api will be hit. When this api is called, it returns a promise. To handle the promise, we use “.then”.


After deleting the data, getData() function will be called to refresh the page and remove the deleting data.


Start the browser on typing the command in the command prompt -


npm start


Output:

The output will be


Register page:-


Login Page:-


Dashboard page:-


Edit page:-


No comments:

Post a Comment

Make new Model/Controller/Migration in Laravel

  In this article, we have included steps to create a model and controller or resource controller with the help of command line(CLI). Here w...