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

.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

Usage Of CancellationToken In Asp.Net Core Applications

When To Use CancellationToken?: In a web application request abortion or orphan, requests are quite common. On users disconnected by network interruption or navigating between multiple pages before proper response or closing of the browser, tabs make the request aborted or orphan. An orphan request can't deliver a response to the client, but it will execute all steps(like database calls, HTTP calls, etc) at the server. Complete execution of an orphan request at the server might not be a problem generally if at all requests need to work on time taking a job at the server in those cases might be nice to terminate the execution immediately. So CancellationToken can be used to terminate a request execution at the server immediately once the request is aborted or orphan. Here we are going to see some sample code snippets about implementing a CancellationToken for Entity FrameworkCore, Dapper ORM, and HttpClient calls in Asp.NetCore MVC application. Note: The sample codes I will show in

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

Blazor WebAssembly Custom Authentication From Scratch

In this article, we are going to explore and implement custom authentication from the scratch. In this sample, we will use JWT authentication for user authentication. Main Building Blocks Of Blazor WebAssembly Authentication: The core concepts of blazor webassembly authentication are: AuthenticationStateProvider Service AuthorizeView Component Task<AuthenticationState> Cascading Property CascadingAuthenticationState Component AuthorizeRouteView Component AuthenticationStateProvider Service - this provider holds the authentication information about the login user. The 'GetAuthenticationStateAsync()' method in the Authentication state provider returns user AuthenticationState. The 'NotifyAuthenticationStateChaged()' to notify the latest user information within the components which using this AuthenticationStateProvider. AuthorizeView Component - displays different content depending on the user authorization state. This component uses the AuthenticationStateProvider

How Response Caching Works In Asp.Net Core

What Is Response Caching?: Response Caching means storing of response output and using stored response until it's under it's the expiration time. Response Caching approach cuts down some requests to the server and also reduces some workload on the server. Response Caching Headers: Response Caching carried out by the few Http based headers information between client and server. Main Response Caching Headers are like below Cache-Control Pragma Vary Cache-Control Header: Cache-Control header is the main header type for the response caching. Cache-Control will be decorated with the following directives. public - this directive indicates any cache may store the response. private - this directive allows to store response with respect to a single user and can't be stored with shared cache stores. max-age - this directive represents a time to hold a response in the cache. no-cache - this directive represents no storing of response and always fetch the fr

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

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

Different HttpClient Techniques To Consume API Calls In Minimal API[.NET6]

In this article, we are going to implement different HttpClient techniques to consume API calls in minimal API. The different HttpClient techniques that we are going to explore are like: Register HttpClient Object Explicitly In DI(Dependency Injection Service) Named Client Type Client HttpRequestMessage Object Create A .NET6 Minimal API Project: Let's create a .Net6 Minimal API sample project 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. CLI command For Minimal API Project dotnet new webapi -minimal -o Your_Project_Name Create A Third Party API Response Model: Here I'm going to use a free third-party rest API that is "https://jsonplaceholder.typicode.com/posts". So to receive the response let's create a response model like 'Post.cs'. Program.cs:(Add Post.cs c

.Net5 Web API Managing Files Using Azure Blob Storage

In this article, we are going to understand the different file operations like uploading, reading, downloading, and deleting in .Net5 Web API application using Azure Blob Storage. Azure Blob Storage: Azure blob storage is Microsoft cloud storage. Blob storage can store a massive amount of file data as unstructured data. The unstructured data means not belong to any specific type, which means text or binary data. So something like images or pdf or videos to store in the cloud, then the most recommended is to use the blob store. The key component to creating azure blob storage resource: Storage Account:- A Storage account gives a unique namespace in Azure for all the data we will save. Every object that we store in Azure Storage has an address. The address is nothing but the unique name of our Storage Account name. The combination of the account name and the Azure Storage blob endpoint forms the base address for each object in our Storage account. For example, if our Storage Account is n

.Net5 Web API Redis Cache Using StackExchange.Redis.Extensions.AspNetCore Library

In this article, we are going to explore the integration of Redis cache in .Net5 Web API application using the 'StackExchange.Redis.Exntensions' library. Note:- Microsoft has introduced an 'IDistributedCache' interface in dotnet core which supports different cache stores like In-Memory, Redis, NCache, etc. It is simple and easy to work with  'IDistributedCache', for the Redis store with limited features but if we want more features of the Redis store we can choose to use 'StackExchange.Redis.Extensions'.  Click here for Redis Cache Integration Using IDistributedCache Interface . Overview On StackExchange.Redis.Extnesions Library: The 'StackExchange.Redis.Extension' library extended from the main library 'StackExchange.Redis'. Some of the key features of this library like: Default serialization and deserialization. Easy to save and fetch complex objects. Search key. Multiple Database Access Setup Redis Docker Instance: For this sampl