The main objectives of this article are:
- Create A HTTP Post Endpoint In The NestJS Application.
- React App To Consume HTTP Post Endpoin
Create A HTTP Post Endpoint In The NestJS Application:
In our service file implement the logic to save a new document to the MongoDB.
NestJS_App/src/employee/employee.service.ts:
async create(employee: Employee) { const newEmployee = new this.employeeModel(employee); return await newEmployee.save(); }
- Here our payload 'employee' is converted to the MongoDB collection model document type using the 'employeeModel' and then invoking the 'save()' method that saves our new document into the MongoDB collection.
NestJS_App/src/employee/employee.controller.ts:
import { Body, Controller, Get, Post } from '@nestjs/common'; import { EmployeeService } from './employee.service'; import { Employee } from './schema/employee-schema'; @Controller('employee') export class EmployeeController { constructor(private employeeService: EmployeeService) {} @Post() async create(@Body() employee: Employee) { return await this.employeeService.create(employee); } }
- (Line: 9) The '@Post()' decorator makes our action method only invoke for the HTTP Post request.
- (Line: 10) The '@Body()' decorator helps to read the form data. Here reading the user posted form data as 'Employee' type.
- (Line: 11) Invoking the 'create()' method of service to save our new item. Finally, return the newly created document as a response.
Create React Component 'AddEmployee':
Let's create a new React component like 'AddEmployee'.
src/pages/AddEmployee.js:
const AddEmployee = () => { return <></>; }; export default AddEmployee;Add the route for the 'AddEmployee' component in the 'App' component.
src/App.js:
import "./App.css"; import Layout from "./components/shared/Layout"; import { Route, Routes } from "react-router-dom"; import AllEmployees from "./pages/AllEmployees"; import AddEmployee from "./pages/AddEmployee"; function App() { return ( <Layout> <Routes> <Route path="/" element={<AllEmployees />}></Route> <Route path="/add-employee" element={<AddEmployee />}></Route> </Routes> </Layout> ); } export default App;
NestJS HTTP Post Endpoint Consume From ReactJS(Read Operation):
Let's try to implement the read operation by consuming the NestJS HTTP Post endpoint from ReactJS.
ReactJS_App/src/pages/AddEmployee.js:
import axios from "axios"; import { useRef } from "react"; import { Button, Col, Container, Row, Form } from "react-bootstrap"; import { useNavigate } from "react-router-dom"; const AddEmployee = () => { const name = useRef(""); const role = useRef(""); const experience = useRef(""); const navigate = useNavigate(); const addEmployeeHandler = () => { var payload = { name: name.current.value, role: role.current.value, experience: experience.current.value, }; axios.post("http://localhost:4000/employee", payload).then(() => { navigate("/"); }); }; return ( <> <Container className="mt-2"> <Row> <Col className="col-md-8 offset-md-2"> <legend>Add New Emplyee Details</legend> <Form.Group className="mb-3" controlId="formName"> <Form.Label>Name</Form.Label> <Form.Control type="text" ref={name} /> </Form.Group> <Form.Group className="mb-3" controlId="formRole"> <Form.Label>Job Role</Form.Label> <Form.Control type="text" ref={role} /> </Form.Group> <Form.Group className="mb-3" controlId="formExperience"> <Form.Label>Experience</Form.Label> <Form.Control type="text" ref={experience} /> </Form.Group> <Button type="button" variant="primary" onClick={addEmployeeHandler} > Add </Button> </Col> </Row> </Container> </> ); }; export default AddEmployee;
- The 'useRef()' loads from the 'react' library. This variable of type 'useRef' can be mapped with the 'ref' attribute of an HTML tag so that we can access the element values with it. So it is very useful for reading the form data.
- (Line: 7-9) Here constant variables is initialized with 'useRef', so all these variables will be mapped with form fields to read the field values.
- (Line: 12-21) The 'addEmplyeeHandler' is a function that holds logic to post the form data to the HTTP Post API call.
- (Line: 13-17) API payload object and here we can observe that to read the form field values we are using eg: 'name.current.value' which means we are accessing the reference of the HTML element to read its values.
- (Line: 18-20) Axios post call invocation on success navigating back to the home page.
- (Line: 29-40) Each form field is mapped to the 'ref' attribute to get access of the form fields.
- (Line: 41-47) Submit button added and its click event can be raised using the 'onClick'. Here we need to register our 'addEmplyeeHandler' to the 'onClick' event.
ReactJS_App/src/AllEmployees.js:
import { useEffect, useState } from "react"; import { Container, Table, Row, Col, Button } from "react-bootstrap"; import axios from "axios"; import { useNavigate } from "react-router-dom"; const AllEmployees = () => { const [employees, setEmployees] = useState([]); const navigate = useNavigate(); useEffect(() => { axios.get("http://localhost:4000/employee").then((response) => { setEmployees(response.data); }); }); return ( <> <Container className="mt-2"> <Row> <Col className="col-md-4 offset-md-4"> <Button variant="primary" type="button" onClick={() => navigate('/add-employee')}> Add </Button> </Col> </Row> <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;
- (Line: 8) Initialized the 'useNavigate()' that loads from the 'react-router-dom'.
- (Line: 21-23) The button registered with a click event that navigates to '/add-employee' route.
(Step 2)
(Step 3)
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-3 | 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-3 | 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