The main objectives of this article are:
- Create HTTP Get Endpoint In NestJS Application.
- Install & Configure React Routing Library In ReactJS Application.
- Create React Component 'AllEmployee'
- Install Axios Library
Create HTTP Get Endpoint In NestJS Application:
In 'EmployeeService' implement logic to fetch data from the MongoDB.
NestJS_App/src/employee/employee.service.ts:
import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { Employee, EmployeeDocument } from './schema/employee-schema'; @Injectable() export class EmployeeService { constructor( @InjectModel(Employee.name) private employeeModel: Model<EmployeeDocument>, ) {} async getAll() { return await this.employeeModel.find().exec(); } }
- The 'find()' method fetches all the documents from the MongoDB collection.
nest g controller employee --no-spec
Now let's add the HTTP GET endpoint in our 'EmployeeController'.
NestJS_App/src/employee/employee.controller.ts:
import { Controller ,Get} from '@nestjs/common'; import { EmployeeService } from './employee.service'; @Controller('employee') export class EmployeeController { constructor(private employeeService:EmployeeService){} @Get() async getAll(){ return await this.employeeService.getAll(); } }
- (Line: 4) To make our 'EmployeeController' class a controller it has to be decorated with '@controller' that loads from the '@nestjs/common'. The '@controller' takes a string as input, which will be part of our endpoint.
- (Line: 7) Injected our 'EmployeeServie'.
- (Line: 8) The '@Get()' decorator makes our method that can be only consumed by the HTTP Get request.
Install & Configure React Routing Library In ReactJS App:
Let's install the react routing library
npm i react-router-dom
Add the 'BrowserRouter' element in the 'index.js'.
React_App/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 React Component 'AllEmployees':
Let's create React component like 'AllEmployees' in the 'pages' folder(new folder).
ReactJS_App/src/pages/AllEmployees.js:
const AllEmployees = () => { return <></>; }; export default AllEmployees;Add the route for the 'AllEmployees' component in the 'App' component.
ReactJS_App/src/App.js:
import logo from "./logo.svg"; import "./App.css"; import Layout from "./components/shared/Layout"; import { Route, Routes } from "react-router-dom"; import AllEmployees from "./pages/AllEmployees"; function App() { return ( <Layout> <Routes> <Route path="/" element={<AllEmployees />}></Route> </Routes> </Layout> ); } export default App;
- Here 'Routes', and 'Route' components are loading from the 'react-router-dom'.
- Inside of our 'Layout' component adds the 'Routes' component and 'Route' as its child components.
- For each 'Route' component, we set up properties like 'path' to configure the route and an 'element' to map the component that needs to be loaded for the matching route.
Install Axios Library:
Let's install the Axios library.
npm i axios
ReactJS App Invokes HTTP GET Endpoint Of NestJS App(Read Operation):
Let's try to invoke the HTTP Get endpoint of the NestJS App from our React App.
ReactJS_App/src/pages/AllEmployees.js:
import { useEffect, useState } from "react"; import { Container, Table } from "react-bootstrap"; import axios from "axios"; const AllEmployees = () => { const [employees, setEmployees] = useState([]); useEffect(() => { axios.get("http://localhost:4000/employee").then((response) => { setEmployees(response.data); }); },[]); return ( <> <Container className="mt-2"> <Table striped bordered hover> <thead> <tr> <th>Name</th> <th>Job Role</th> <th>Experience</th> </tr> </thead> <tbody> {employees.map((emp) => ( <tr key={emp._id}> <td>{emp.name}</td> <td>{emp.role}</td> <td>{emp.experience}</td> </tr> ))} </tbody> </Table> </Container> </> ); }; export default AllEmployees;
- 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 components gets refreshed(component re-executed). 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 second value will be the function to update the state.
- The 'useEffect' loads from the 'react' library. The 'useEffect(() => {},[])' contains 2 input parameters where the first parameter is arrow function in which we can write our logic to executes and second parameter is arraay 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: 6) Declare the 'useState' where it value will assigned to 'employees' variable and to update the value we can use 'setEmployee' function.
- (Line: 8-12) Here we 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 the 'employee' by using 'setEmplyee'.
- (Line: 26-32) Render our API response using 'map()' looping the bootstrap table rows. To render a dynamic content we have to encapsulate it inside of single '{}' braces.
Now if we run the application and try to navigate to 'http://localhost:3000' we can see consumption API fails due cors issue. Because our API and ReactJS are having different domains(nothing but localhost with different ports) so cors will occur. So let's enable the cors at our NestJS application so that we can resolve the cors issue.
NestJS_App/src/main.ts:
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.enableCors() await app.listen(4000); } bootstrap();
- (Line: 7) Here enabled 'cors' in our NestJS application.
Support Me!
Buy Me A Coffee
PayPal Me
Video Session:
Wrapping Up:
Hopefully, I think this article delivered some useful information on NestJS(v9) | ReactJS(v18) CRUD sample. I love to have your feedback, suggestions, and better techniques in the comment section below.
Refer:
Part-1 | NestJS(v9) | ReactJS(v18) | MongoDB | CRUD Example
Part-2 | NestJS(v9) | ReactJS(v18) | MongoDB | CRUD Example
Part-4 | NestJS(v9) | ReactJS(v18) | MongoDB | CRUD Example
Part-5 | NestJS(v9) | ReactJS(v18) | MongoDB | CRUD Example
Part-6 | NestJS(v9) | ReactJS(v18) | MongoDB | CRUD Example
Part-2 | NestJS(v9) | ReactJS(v18) | MongoDB | CRUD Example
Part-4 | NestJS(v9) | ReactJS(v18) | MongoDB | CRUD Example
Part-5 | NestJS(v9) | ReactJS(v18) | MongoDB | CRUD Example
Part-6 | NestJS(v9) | ReactJS(v18) | MongoDB | CRUD Example
Comments
Post a Comment