Skip to main content

ReactJS(V18) CRUD Example

In this article, we will implement CRUD operation in ReactJS(v18) application.

ReactJS:

ReactJS is a javascript library for creating user interface components. ReactJS components contains javascript function and they return JSX(JavaScript XML) as output. ReactJS effectively renders and update component on data changes.

Create ReactJS(v18) Application:

To create a ReactJS application our local machine should contain NodeJS. So go to 'https://nodejs.org/en/download/'

Command to create ReactJS application
npx create-react-app name-of-your-app

Command to start the application.
npm start

Let's go through the project and explore important files.

index.html: Inside the public folder we can see the index.html. Only the HTML file of the entire ReactJS application. It contained a 'div' element whose 'id' value is 'root', inside of this element all ReactJS components get rendered.

index.js: Entry javascript file for ReactJS. It helps paint 'App' component content in 'index.html'.

App.js: The 'App.js' react component. It returns the 'JSX'(Javascript XML) content(JSX means writing the HTML code inside of javascript directly).

Install ReactJS Bootstrap:

ReactJS Bootstrap library built on top of normal bootstrap. ReactJS Bootstrap UI components are very easy to integrate with the ReactJS app.
npm install react-bootstrap bootstrap

Now add the bootstrap CSS file reference to the 'index.js'
src/index.js:
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import "bootstrap/dist/css/bootstrap.min.cs";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
  • (Line: 5) Added the bootstrap CSS file reference.
  • Here we removed the existing code like 'reportWebVitals' and 'React.StrictMode'.

Add React Bootstrap Menu:

Now, 'Menu' will be shared content must be displayed for every page on the application. So let's create a shared component like 'Layout.js' inside of the 'components/shared' folders(new folders).
src/component/shared/Layout.js:
import Container from 'react-bootstrap/Container';
import Navbar from 'react-bootstrap/Navbar';

function Layout(props) {
  return (
    <div>
        <Navbar expand="lg" variant="dark" bg="success">
          <Container>
            <Navbar.Brand >Fruits Bucket</Navbar.Brand>
          </Container>
        </Navbar>
      <Container>{props.children}</Container>
    </div>
  );
}
export default Layout;
  • Here 'Layout' is our component function entire logic is added inside of it and this function returns JSX content. The 'Layout' function has input parameters like 'props' which gives access to either custom or default properties.
  • (Line: 1&2) Imported the react-bootstrap component like 'Container' & 'Navbar'.
  • (Line: 12) The 'Layout' function must be render as custom tag like '<Layout></Layout>'. So to read the content inside of the 'Layout' element we have to use 'props.children' and to render the content we have to use ReactJS expression like '{}'(this can render plain text, HTML, and even executes logical expressions).
Since 'App.js' is the entry component of our application, so let's encapsulate the content indie of the 'Layout' element tag as follows.
src/App.js:
import "./App.css";
import Layout from "./components/shared/Layout";
function App() {
  return <Layout><h1>Welcome!</h1></Layout>;
}
export default App;

Setup JSON Server:

Let's set up a fake API by setting up the JSON server in our local machine.

Run the below command to install the JSON server globally onto your local system.
npm install -g json-server

For our demo purpose go to the ReactJS application and the following command to the 'package.json' file. By default, the JSON server runs on port number 3000, ReactJS also runs on the same portal locally so here we specify another port number explicitly.
"json-server":"json-server --watch db.json --port 4000"


Now to invoke the above command run the following command in the ReactJS app root folder.
npm run json-server

After running the above command for the first time, a 'db.json' file gets created, so this file act as a database. So let's add some sample data to the file below.

Now access the API endpoint like 'http://localhost:4000/fruits'.

Create A ReactJS Component 'AllFruits':

Let's create a new ReactJS component like 'AllFruits' inside of the new folder 'pages'.
src/pages/AllFruits.js:
function AllFruits() {
  return <></>;
}
export default AllFruits;

Install Axios Library:

To invoke the API calls from our ReactJS application most recommended library is 'Axios'. Let's install the 'Axios' library
npm i axios

Display API Response In 'AllFruits' Component(Read Operation):

Let's implement the Read Operation by invoking the API call and then render the response in the 'AllFruits' component.
src/pages/AllFruits.js:
import axios from "axios";
import { useEffect, useState } from "react";
import Card from "react-bootstrap/Card";
import Col from "react-bootstrap/Col";
import Row from "react-bootstrap/Row";

function AllFruits() {
  const [allFruits, setAllFruits] = useState([]);

  useEffect(() => {
    axios.get("http://localhost:4000/fruits").then((response) => {
      setAllFruits(response.data);
    });
  }, []);

  return (
    <>
      <Row xs={1} md={3} className="g-2">
        {allFruits.map((item) => (
          <Col key={item.id}>
            <Card>
              <Card.Img variant="top" src={item.imageUrl} />
              <Card.Body>
                <Card.Title>{item.name}</Card.Title>
                <Card.Text>Quantity(KG Units) - {item.quantity}</Card.Text>
                <Card.Text>Price - {item.price}</Card.Text>
              </Card.Body>
            </Card>
          </Col>
        ))}
      </Row>
    </>
  );
}
export default AllFruits;
  • The 'useState' loads from the 'react' library. In ReactJS application to maintain a state of data, we will use the 'useState'. If the value of 'useState' variable changes entire component gets refreshed(reexecutes). The default values can be given while it is initialized. The 'useState' return array of 2 values, where the first value will be the data and the second value will be the function to update the state.
  • The 'useEffect' loads from the 'react' library. The 'useEffect(() => {},[])' contains 2 input parameters where first parameter is arrow function in which we can write our logic to executes and second parameter is array to which we can pass 'useState' values. So whenever the second parameter value changes then only the 'useEffect' gets executed. If the second parameter array is empty then 'useEffect' get executes only once.
  • (Line: 8) Declared the 'useState' where its value will be accessed through 'allFruits' and to update it we have to use the'setAllFurits' function.
  • (Line: 10-14) Here used the 'useEffect' where we implemented our Axois API call logic. So to execute the logic inside of 'useEffect' only once we passed the second parameter as an empty array. After API success the response is assigned to 'allFruits' by setting the 'setAllFruits'.
  • (Line: 18) Used ReactJS bootstrap 'Row' component and specified its property like 'md={3}' only render 3 columns from medium size screens and another property like 'xs={1}' only reander 1 column for extra-small screens(mobiles).
  • (Line: 19) The 'allFruits' state variable which contains API response is looping to render the data.
  • (Line: 20) The 'Col' component specified the 'key' property which is recommended to provide unique value for looping items.
  • (Line: 22-26) In ReactJS to render dynamic data, we have used single flower braces '{}'.
Now let's render the 'AllFruits' component in 'App' component.
src/App.js:
import "./App.css";
import Layout from "./components/shared/Layout";
import AllFruits from "./pages/AllFruits";

function App() {
  return (
    <Layout>
      <AllFruits></AllFruits>
    </Layout>
  );
}

export default App;
Now run our ReactJ application and our JSON server.
(Step 1)

(Step 2)

Create A ReactJS Component 'AddFruit':

In the 'pages' folder let's add a new ReactJS component like 'AddFruit'.
src/pages/AddFruit.js:
function AddFruit() {
  return <></>;
}
export default AddFruit;

Install React Router Package And Configure Routes:

Let's install the React Router package.
npm i react-router-dom


Now add routing for each ReactJS component at the 'App' component.
src/App.js:
import { Routes, Route } from "react-router-dom";
import "./App.css";
import Layout from "./components/shared/Layout";
import AddFruit from "./pages/AddFruit";
import AllFruits from "./pages/AllFruits";

function App() {
  return (
    <Layout>
      <Routes>
        <Route path="/" element={<AllFruits />}></Route>
        <Route path="/add-fruit" element={<AddFruit />}></Route>
      </Routes>
    </Layout>
  );
}
export default App;
  • Here 'Routes', and 'Route' components are loading from the 'react-router-dom'.
  • Inside of our 'Layout' component add the 'Routes' component and 'Route' are its child component.
  • For each 'Route' component, we set up properties like 'path' to configure the route and an 'element' to map the component that needs load for the matching route.
In 'index.js' we have to configure the 'BrowserRouter' component that loads from the 'react-router-dom'.
src/index.js:
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import "bootstrap/dist/css/bootstrap.min.css";
import { BrowserRouter } from "react-router-dom";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<BrowserRouter><App /></BrowserRouter>);

Create Form To Consume HTTP Post API Call In 'AddFruit' Component(Create Operation):

Let's implement the logic to create a new item by invoking the HTTP Post API call in the 'AddFruit' component.
src/pages/AddFruit.js:
import axios from "axios";
import { useRef } from "react";
import Button from "react-bootstrap/Button";
import Form from "react-bootstrap/Form";
import { useNavigate } from "react-router-dom";

function AddFruit() {
  const fruitName = useRef("");
  const quantity = useRef("");
  const price = useRef("");
  const imageUrl = useRef("");

  const navigate = useNavigate();

  const addFruitHandler = () => {
    var payload = {
      name: fruitName.current.value,
      quantity: quantity.current.value? Number(quantity.current.value):0,
      price: price.current.value ? Number(price.current.value): 0 ,
      imageUrl: imageUrl.current.value,
    };
    axios.post("http://localhost:4000/fruits", payload).then(() => {
      navigate("/");
    });
  };
  return (
    <>
      <legend>Create</legend>
      <Form>
        <Form.Group className="mb-3" controlId="formName">
          <Form.Label>Name</Form.Label>
          <Form.Control type="text" ref={fruitName} />
        </Form.Group>
        <Form.Group className="mb-3" controlId="formQuanity">
          <Form.Label>Quantity(KG Units)</Form.Label>
          <Form.Control type="number" ref={quantity} />
        </Form.Group>
        <Form.Group className="mb-3" controlId="formPrice">
          <Form.Label>Price</Form.Label>
          <Form.Control type="number" ref={price} />
        </Form.Group>
        <Form.Group className="mb-3" controlId="formImageUrl">
          <Form.Label>ImageUrl</Form.Label>
          <Form.Control type="text" ref={imageUrl} />
        </Form.Group>
        <Button variant="primary" type="button" onClick={addFruitHandler}>
          Add
        </Button>
      </Form>
    </>
  );
}
export default AddFruit;
  • The 'useRef' loads from the 'react' library. The 'useRef' can be used to read the instance of the HTML elements.
  • (Line: 8-11) Declared and initialized the 'useRef' variable, each variable represents a form field for reading the user entered form data.
  • (Line: 13) Declared 'navigate' variable of type 'useNavigate()'. The 'useNaviget()' loads from the 'react-router-dom'. It helps navigate between the react components.
  • (Line: 15-25) Add the 'addFruitHandler' method, it contains logic to invoke the API call to create a new item. Here payload is prepared with our 'useRef' variable from which we fetch form data. On the success of API call navigate back to home page.
  • (Line: 32&36&40&44) Here 'Form.Control' decorated with 'ref' attribute that is assigned to our 'useRef' variables. So 'ref' attribute passes the HTML element instances to the 'useRef' variables.
  • (Line: 46-48) The 'Add' button whose 'onclick' registered to 'addFruitHandler' method.
Now to create an item, we need navigation from the 'AllFruits' component to the 'AddFruit' form component. So in the 'AllFruits' component configure a button like 'Add A New Fruit'.
src/pages/AllFruits.js:
import axios from "axios";
import { useEffect, useState } from "react";
import Card from "react-bootstrap/Card";
import Col from "react-bootstrap/Col";
import Row from "react-bootstrap/Row";
import { useNavigate } from "react-router-dom";
import Button from "react-bootstrap/Button";

function AllFruits() {
  const [allFruits, setAllFruits] = useState([]);
  const navigate = useNavigate();

  useEffect(() => {
    axios.get("http://localhost:4000/fruits").then((response) => {
      setAllFruits(response.data);
    });
  }, []);

  return (
    <>
      <Row className="mt-2">
        <Col md={{ span: 4, offset: 4 }}>
          <Button variant="primary" onClick={() => navigate("/add-fruit")}>
            Add New Fruit
          </Button>
        </Col>
      </Row>
      <Row xs={1} md={3} className="g-2">
        {allFruits.map((item) => (
          <Col key={item.id}>
            <Card >
              <Card.Img variant="top" src={item.imageUrl} style={{height:300}} />
              <Card.Body>
                <Card.Title>{item.name}</Card.Title>
                <Card.Text>Quantity(KG Units) - {item.quantity}</Card.Text>
                <Card.Text>Price - {item.price}</Card.Text>
              </Card.Body>
            </Card>
          </Col>
        ))}
      </Row>
    </>
  );
}
export default AllFruits;
  • (Line: 11) Declared the 'navigate' variable of type 'useNavigate()'. The 'useNavigate()' loads from the 'react-router-dom'.
  • (Line: 23-25) Configured the 'Add New Fruit' button whose 'onClick' event registers with an arrow function that contains navigation logic.
(Step 1)

(Step 2)

(Step 3)

Create A ReactJS Component 'UpdateFruit':

In the 'pages' folder let's add a new ReactJS component like 'UpdateFruit'.
src/pages/UpdateFruit.js:
function UpdateFruit() {
  return <></>;
}
export default UpdateFruit;
Now configure the route for the 'UpdateFruit' component in the 'App' component.
src/App.js:
import { Routes, Route } from "react-router-dom";
import "./App.css";
import Layout from "./components/shared/Layout";
import AddFruit from "./pages/AddFruit";
import AllFruits from "./pages/AllFruits";
import UpdateFruit from "./pages/UpdateFruit";

function App() {
  return (
    <Layout>
      <Routes>
        <Route path="/" element={<AllFruits />}></Route>
        <Route path="/add-fruit" element={<AddFruit />}></Route>
        <Route path="/update-fruit/:id" element={<UpdateFruit />}></Route>
      </Routes>
    </Layout>
  );
}
export default App;
  • (Line: 14) Configured route for 'UpdateFruit' component. Here we can observe dynamic route placeholders like ':id' which means our item 'id' value will be passed.

Edit Form To Consume HTTP Put API Call In 'UpdateFruit' Component(Update Operation):

Let's implement the 'Edit' form in the 'UpdateFruit' component on the submitting form send the data to the HTTP Put endpoint.
src/pages/UpdateFruit.js:
import axios from "axios";
import { useEffect, useRef } from "react";
import { useNavigate, useParams } from "react-router-dom";
import Button from "react-bootstrap/Button";
import Form from "react-bootstrap/Form";

function UpdateFruit() {
  const fruitName = useRef("");
  const quantity = useRef("");
  const price = useRef("");
  const imageUrl = useRef("");

  const { id } = useParams();

  const navigate = useNavigate();

  useEffect(() => {
    axios.get(`http://localhost:4000/fruits/${id}`).then((response) => {
      fruitName.current.value = response.data.name;
      quantity.current.value = response.data.quantity;
      price.current.value = response.data.price;
      imageUrl.current.value = response.data.imageUrl;
    });
  }, []);

  const updateFruitHandler = () => {
    var payload = {
      name: fruitName.current.value,
      quantity: quantity.current.value ? Number(quantity.current.value) : 0,
      price: price.current.value ? Number(price.current.value) : 0,
      imageUrl: imageUrl.current.value,
    };

    axios.put(`http://localhost:4000/fruits/${id}`, payload).then((response) => {
        navigate("/");
    })
  };

  return (
    <>
      <legend>Update</legend>
      <Form>
        <Form.Group className="mb-3" controlId="formName">
          <Form.Label>Name</Form.Label>
          <Form.Control type="text" ref={fruitName} />
        </Form.Group>
        <Form.Group className="mb-3" controlId="formQuanity">
          <Form.Label>Quantity(KG Units)</Form.Label>
          <Form.Control type="number" ref={quantity} />
        </Form.Group>
        <Form.Group className="mb-3" controlId="formPrice">
          <Form.Label>Price</Form.Label>
          <Form.Control type="number" ref={price} />
        </Form.Group>
        <Form.Group className="mb-3" controlId="formImageUrl">
          <Form.Label>ImageUrl</Form.Label>
          <Form.Control type="text" ref={imageUrl} />
        </Form.Group>
        <Button variant="primary" type="button" onClick={updateFruitHandler}>
          Update
        </Button>
      </Form>
    </>
  );
}
export default UpdateFruit;
  • (Line: 8-11) Declared the 'useRef' variables which we use to read the form data.
  • (Line: 13) The 'useParams()' loads from the 'react-router-dom' helps to read the dynamic data from the route.
  • (Line: 15) Declared 'navigate' variable of type 'useNavigate()'.
  • (Line: 17-24) Here invoking the API by the 'id' value. It needs to be invoked only once on component rendering so it's invoked inside of the 'useEffect'.
  • (Line: 26-37) Created the 'updateFruitHandler' method which invokes HTTP PUT API call.
  • (Line: 59-60) Configured 'Update' button whose click event registered with 'updateFruitHandler'.
Now configure the 'Edit' button 'AllFruits' component that helps to navigate from 'AllFruits' component to the 'UpdateFruit' component.
src/pages/AllFruits.js:
// existing code hidden for display purpose
<Card.Body>
	<Card.Title>{item.name}</Card.Title>
	<Card.Text>Quantity(KG Units) - {item.quantity}</Card.Text>
	<Card.Text>Price - {item.price}</Card.Text>
	<Button
	  variant="primary"
	  onClick={() => navigate(`/update-fruit/${item.id}`)}
	>
	  Edit
	</Button>
</Card.Body>
  • (Line: 6-11) The 'Edit' button click  event registered with the arrow function. The arrow function contains logic to navigate to 'UpdateFruit' component.
(Step 1)
(Step 2)

(Step 3)

Create 'DeleteConfirmation' React Component:

Let's create a new React component like 'DeleteConfirmation'. This is not going to be a page component, but i want make it as a shared component so that anywhere we can use this 'DeleteConfiramtion' component so create this component in 'components/shared' folders.
src/components/shared/DeleteConfirmation.js:
import Button from "react-bootstrap/Button";
import Modal from "react-bootstrap/Modal";

function DeleteConfirmation(props) {
  return (
    <>
      <Modal
        show={props.showModal}
        onHide={() => {
          props.hideDeleteModalHandler();
        }}
      >
        <Modal.Header closeButton>
          <Modal.Title>{props.title}</Modal.Title>
        </Modal.Header>
        <Modal.Body>{props.body}</Modal.Body>
        <Modal.Footer>
          <Button
            variant="secondary"
            onClick={() => {
              props.hideDeleteModalHandler();
            }}
          >
            Close
          </Button>
          <Button
            variant="primary"
            onClick={() => {
              props.confirmDeleteHandler();
            }}
          >
            Confirm Delete
          </Button>
        </Modal.Footer>
      </Modal>
    </>
  );
}
export default DeleteConfirmation;
  • Here 'DeleteConfirmation' component contains react-bootstrap modal code.
  • (Line: 8) The 'show' is the boolean property of the 'Modal' component. The parent component passes its value through 'props.showModal'(here showModal is our custom property name which must be passed by the parent component and its value should be boolean). So if 'show' property receives 'true' then opens the modal.
  • (Line: 9-11) The 'onHide' get triggered by the 'X'(close button) on the rigth-top corner of the modal. Here 'onHide' register with an arrow function which internally calls a method of the parent component like 'props.hideDeleteModalHandler'.
  • (Line: 14) Dynamic 'props.title' property for the modal title.
  • (Line: 16) Dynamic 'props.body' property for the modal body.
  • (Line: 18-25) Close button click event register with arrow function which internally calls a method of parents component like 'props.hideDeleteModalHandler'.
  • (Line: 26-33) Confirm delete button, click event register with arrow function which internally calls a method of parents component like 'props.confirmDeleteHandler'.

Invoke 'DeleteConfirmation' From 'AllFruits' Component(Delete Operation):

Let's add the 'DeleteConfirmation' element into our 'AllFruits' component so that whenever we click on the delete button 'DeleteConfimation' modal will open.
src/pates/AllFruits.js:
import axios from "axios";
import { useEffect, useState } from "react";
import Card from "react-bootstrap/Card";
import Col from "react-bootstrap/Col";
import Row from "react-bootstrap/Row";
import { useNavigate } from "react-router-dom";
import Button from "react-bootstrap/Button";
import DeleteConfirmation from "../components/shared/DeleteConfirmation";

function AllFruits() {
  const [allFruits, setAllFruits] = useState([]);
  const navigate = useNavigate();

  const [showModal, setShowModal] = useState(false);
  const [itemToDeleteId, setItemToDeleteId] = useState(0);

  useEffect(() => {
    axios.get("http://localhost:4000/fruits").then((response) => {
      setAllFruits(response.data);
    });
  }, []);

  const openConfirmDeleteModalHandler = (id) => {
    setShowModal(true);
    setItemToDeleteId(id);
  };

  const hideDeleteModalHandler = () => {
    setShowModal(false);
    setItemToDeleteId(0);
  };

  const confirmDeleteHandler = () => {
    axios
      .delete(`http://localhost:4000/fruits/${itemToDeleteId}`)
      .then((response) => {
        setAllFruits((previousState) => {
          return previousState.filter((_) => _.id !== itemToDeleteId);
        });
        setItemToDeleteId(0);
        setShowModal(false);
      });
  };

  return (
    <>
      <DeleteConfirmation
        showModal={showModal}
        hideDeleteModalHandler={hideDeleteModalHandler}
        title="Delete Confirmation"
        body="Are you want delete this itme?"
        confirmDeleteHandler={confirmDeleteHandler}
      ></DeleteConfirmation>
      <Row className="mt-2">
        <Col md={{ span: 4, offset: 4 }}>
          <Button variant="primary" onClick={() => navigate("/add-fruit")}>
            Add New Fruit
          </Button>
        </Col>
      </Row>
      <Row xs={1} md={3} className="g-2">
        {allFruits.map((item) => (
          <Col key={item.id}>
            <Card>
              <Card.Img
                variant="top"
                src={item.imageUrl}
                style={{ height: 300 }}
              />
              <Card.Body>
                <Card.Title>{item.name}</Card.Title>
                <Card.Text>Quantity(KG Units) - {item.quantity}</Card.Text>
                <Card.Text>Price - {item.price}</Card.Text>
                <Button
                  variant="primary"
                  onClick={() => navigate(`/update-fruit/${item.id}`)}
                >
                  Edit
                </Button>
                <Button
                  variant="danger"
                  onClick={() =>{openConfirmDeleteModalHandler(item.id)}}
                >
                  Delete
                </Button>
              </Card.Body>
            </Card>
          </Col>
        ))}
      </Row>
    </>
  );
}
export default AllFruits;
  • (Line: 14) The 'showModal' & 'setShowModal' are useState variables used to show and hide the Modal
  • (Line: 15) The 'itemToDeleteId' & 'setItemToDeleteId' are useState variables used to maintain 'id' of the record need to be deleted.
  • (Line: 23-26) The function 'openConfirmDeleteModalHandler' will invoke by the delete button. It contains logic like 'setShowModal' to true which opens the delete confirmation modal and  'setItemToDelteId' contains the record to be deleted
  • (Line: 28-31) The function 'hideDeleteModalHandler' will invoke by the 'cancel' button on modal. It contains logic like 'setShowModal' to false which closes the modal and 'setItemToDeleteId' reset to value '0'.
  • (Line: 33-43) The function 'confirmDeleteHandler' logic invokes the delete API call. After API success we are updating a few 'useState' variables. The 'setShowModal' is assigned to false to close the modal. The 'setAllFruits' update to remove the deleted item from its array. The 'setItemToDeleteId' value reset to '0'
  • (Line: 47-52) Rendered the 'DeleteConfirmation' component element with all required props
  • (Line: 80-85) The 'Delete' button clicks the event registered with the arrow function it internally invoke the 'openConfirmDeleteModalHandler' by inputting the 'id' of the item to delete.

Support Me!
Buy Me A Coffee PayPal Me

Video Session:

Wrapping Up:

Hopefully, I think this article delivered some useful information on the React JS(v18) CRUD Example. I love to have your feedback, suggestions, and better techniques in the comment section below.

Refer:

Follow Me:

Comments

Popular posts from this blog

Angular 14 Reactive Forms Example

In this article, we will explore the Angular(14) reactive forms with an example. Reactive Forms: Angular reactive forms support model-driven techniques to handle the form's input values. The reactive forms state is immutable, any form filed change creates a new state for the form. Reactive forms are built around observable streams, where form inputs and values are provided as streams of input values, which can be accessed synchronously. Some key notations that involve in reactive forms are like: FormControl - each input element in the form is 'FormControl'. The 'FormControl' tracks the value and validation status of form fields. FormGroup - Track the value and validate the state of the group of 'FormControl'. FormBuilder - Angular service which can be used to create the 'FormGroup' or FormControl instance quickly. Form Array - That can hold infinite form control, this helps to create dynamic forms. Create An Angular(14) Application: Let'

.NET 7 Web API CRUD Using Entity Framework Core

In this article, we are going to implement a sample .NET 7 Web API CRUD using the Entity Framework Core. Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, and desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains programming functions that can be requested via HTTP calls either to fetch or update data for their respective clients. Some of the Key Characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build the REST full services. Install The SQL Server And SQL Management Studio: Let's install the SQL server on our l

ReactJS(v18) JWT Authentication Using HTTP Only Cookie

In this article, we will implement the ReactJS application authentication using the HTTP-only cookie. HTTP Only Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing the JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-ONly cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use the authentication with HTTP-only JWT cookie then we no need to implement the custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To authenticate our client application with JWT HTTP-only cookie, I developed a NetJS(which is a node) Mock API. Check the GitHub link and read the document on G

.NET6 Web API CRUD Operation With Entity Framework Core

In this article, we are going to do a small demo on AspNetCore 6 Web API CRUD operations. What Is Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains a programming function that can be requested via HTTP calls to save or fetch the data for their respective clients. Some of the key characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build REST full services. Create A .NET6 Web API Application: Let's create a .Net6 Web API sample application to accomplish our

Angular 14 State Management CRUD Example With NgRx(14)

In this article, we are going to implement the Angular(14) state management CRUD example with NgRx(14) NgRx Store For State Management: In an angular application to share consistent data between multiple components, we use NgRx state management. Using NgRx state helps to avoid unwanted API calls, easy to maintain consistent data, etc. The main building blocks for the NgRx store are: Actions - NgRx actions represents event to trigger the reducers to save the data into the stores. Reducer - Reducer's pure function, which is used to create a new state on data change. Store - The store is the model or entity that holds the data. Selector - Selector to fetch the slices of data from the store to angular components. Effects - Effects deals with external network calls like API. The effect gets executed based the action performed Ngrx State Management flow: The angular component needs data for binding.  So angular component calls an action that is responsible for invoking the API call.  Aft

Angular 14 Crud Example

In this article, we will implement CRUD operation in the Angular 14 application. Angular: Angular is a framework that can be used to build a single-page application. Angular applications are built with components that make our code simple and clean. Angular components compose of 3 files like TypeScript File(*.ts), Html File(*.html), CSS File(*.cs) Components typescript file and HTML file support 2-way binding which means data flow is bi-directional Component typescript file listens for all HTML events from the HTML file. Create Angular(14) Application: Let's create an Angular(14) application to begin our sample. Make sure to install the Angular CLI tool into our local machine because it provides easy CLI commands to play with the angular application. Command To Install Angular CLI npm install -g @angular/cli Run the below command to create the angular application. Command To Create Angular Application ng new name_of_your_app Note: While creating the app, you will see a noti

Unit Testing Asp.NetCore Web API Using xUnit[.NET6]

In this article, we are going to write test cases to an Asp.NetCore Web API(.NET6) application using the xUnit. xUnit For .NET: The xUnit for .Net is a free, open-source, community-focused unit testing tool for .NET applications. By default .Net also provides a xUnit project template to implement test cases. Unit test cases build upon the 'AAA' formula that means 'Arrange', 'Act' and 'Assert' Arrange - Declaring variables, objects, instantiating mocks, etc. Act - Calling or invoking the method that needs to be tested. Assert - The assert ensures that code behaves as expected means yielding expected output. Create An API And Unit Test Projects: Let's create a .Net6 Web API and xUnit sample applications to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor. Create a fo

Part-1 Angular JWT Authentication Using HTTP Only Cookie[Angular V13]

In this article, we are going to implement a sample angular application authentication using HTTP only cookie that contains a JWT token. HTTP Only JWT Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-Only cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use authentication with HTTP only JWT cookie then we no need to implement custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To implement JWT cookie authentication we need to set up an API. For that, I had created a mock authentication API(Using the NestJS Se

ReactJS(v18) Authentication With JWT AccessToken And Refresh Token

In this article, we are going to do ReactJS(v18) application authentication using the JWT Access Token and Refresh Token. JSON Web Token(JWT): JSON Web Token is a digitally signed and secured token for user validation. The JWT is constructed with 3 important parts: Header Payload Signature Create ReactJS Application: Let's create a ReactJS application to accomplish our demo. npx create-react-app name-of-your-app Configure React Bootstrap Library: Let's install the React Bootstrap library npm install react-bootstrap bootstrap Now add the bootstrap CSS reference in 'index.js'. src/index.js: import 'bootstrap/dist/css/bootstrap.min.css' Create A React Component 'Layout': Let's add a React component like 'Layout' in 'components/shared' folders(new folders). src/components/shared/Layout.js: import Navbar from "react-bootstrap/Navbar"; import { Container } from "react-bootstrap"; import Nav from "react-boot

A Small Guide On NestJS Queues

NestJS Application Queues helps to deal with application scaling and performance challenges. When To Use Queues?: API request that mostly involves in time taking operations like CPU bound operation, doing them synchronously which will result in thread blocking. So to avoid these issues, it is an appropriate way to make the CPU-bound operation separate background job.  In nestjs one of the best solutions for these kinds of tasks is to implement the Queues. For queueing mechanism in the nestjs application most recommended library is '@nestjs/bull'(Bull is nodejs queue library). The 'Bull' depends on Redis cache for data storage like a job. So in this queueing technique, we will create services like 'Producer' and 'Consumer'. The 'Producer' is used to push our jobs into the Redis stores. The consumer will read those jobs(eg: CPU Bound Operations) and process them. So by using this queues technique user requests processed very fastly because actually