Search code examples
react-routerfetchcrudroutermern

how to use router and fetch for crud in mern


I'm trying to learn how can I use router at the backend and fetch function for the frontend in my mern project

I'm trying to understand from others project how they have implemented the router and fetch function in there application

someone please help me to understand I'm currently working on the mern project


Solution

  • Hi I'm sharing the frontend and the router file which I have used in my web app

    FRONTEND as below-

    import React, { Component } from 'rect';
    import "./App.css"
    
    class Label extends Component {
        url = 'http://localhost:8080/courses/'
        state = {
            show: false,
            data: [],
            rating: 1,
        }
        componentDidMount = () => {
    
            this.handelGetData()
    }
    
    handelGetData = () => {
        fetch(this.url + "get")
            .then((res) => res.json())
            .then((json) => {
                this.setState({ data: json })
            })
    }
    
    handelApply = async (id) => {
        const requestOption = {
            method: 'post',
            headers: { 'Content-Type': 'application/json' }
        };
        fetch(this.url + 'enroll/' + id, requestOption)
            .then(() => {
                this.handelGetData()
            })
    }
    
    handelRating = (e) => {
        this.setState({ rating: e.target.value })
    }
    
    handelAddRating = async (id) => {
        const requestOption = {
            method: 'PATCH',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ rating: this.state.rating })
        }
        fetch(this.url + "rating/" + id, requestOption)
            .then(() => {
                this.handelGetData()
            })
    }
    
    handelDrop = async (id) => {
        const requestOption = {
            method: 'DELETE',
            headers: { 'Content-Type': 'application/json' }
        };
        fetch(this.url + "drop/" + id, requestOption)
            .then(() => {
                this.handelGetData()
            })
    }
    
    render() {
        return {
            < div className = "label" >
            <header>
                <h2>leabel heading 1</h2>
            </header>
        {/* write here */ }
        <div className="bottelContainer">
            {this.state.data.map(courses => {
                return {
                    < div className = "bottel" >
                    <ul>
                        <div className="heading">
                            <li>{courses.courseName}</li>
                            <li>{courses.courseDept}</li>
                            <li>{courses.description}</li>
    
                            {courses.isAppied &&
                                <li>
                                    {!courses.isRated &&
                                        <li>Rate:
                                            <select className="rating" name="rating" onChange={this.handelRating}>
                                                <Option>1</Option>
                                                <Option>2</Option>
                                                <Option>3</Option>
                                                <Option>4</Option>
                                                <Option>5</Option>
                                            </select>
                                            <button className="rate" onClick={() => this.handelAddRating(courses._id)}>Submit</button>
                                        </li>
                                    }
                                    {courses.isAppied &&
                                        <button className="drop" onClick={() => this.handelDrop(courses._id)}>Remove</button>
                                    }
                                </li>
                            }
    
                            {!courses.isAppied &&
                                <button className="btn" onClick={() => this.handelApply(courses._id)}>Apply</button>
                            }
                        </div>
                        <div className="footer">
                            <li>{courses.duration} hrs , {courses.noOfRatings} Ratings , {courses.rating}/5</li>
                        </div>
                    </ul>
            </div>
    }
    })}
                
            </div >
                    
                </div >
            }
    }
    }
    

    Router function used in the application as below -

    const express = require("express");
    const { getEnvironmentData } = require("worker_threads");
    const Courses = require("../mongoose/models/courses");
    
    const uRouter = new express.Router();
    
    
    
    uRouter.get('/courses/get', async(req, res) => {
        const data = await Courses.find()
        res.status(200).json(data)
    })
    
    uRouter.post('/courses/enroll/:id', async(req, res) => {
        const id = req.params.id;
        const data = await Courses.findById(id);
        if(!getData.isApplied){
            obj = {
                isApplied: true
            }
            await Courses.findByIdAndUpdate(id, obj)
            res.status(200).json({message: "Enrolled Successfully"})
        }else{
            res.status(403).json({message: "Not Allowed"})
        }
    })
    
    uRouter.patch('/courses/rating/:id', async (req, res) => {
        const id = req.params.id
        const getData = await Courses.findById(id)
        if(!getData.isRated && getData.isApplied){
            const body = req.body
            const noOfRatings = getData.noOfRatings + 1
            const finalRate = (((getData.noOfRatings * getData.rating) + body.rating)/noOfRatings).toFixed(1)
            obj = {
                isRated: true,
                rating: finalRate,
                noOfRatings: noOfRatings
            }
            await Courses.findByIdAndUpdate(id, obj)
            res.status(200).json({message: "Rated Successfully"})
        }else{
            res.status(403).json({message: "Not Allowed"})
        }
    })
    
    uRouter.delete('/courses/drop/:id', async (req, res) => {
        const id = req.params.id
        const getData = await Courses.findById(id)
        if(getData.isApplied) {
            obj = {
                isApplied : false
            }
            await Courses.findByIdAndUpdate(id, obj)
            res.status(200).json({message: "Rated Successfully"})
        }
        else{
            res.status(403).json({message: "Not Allowed"})
        }
    })
    module.exports = uRouter;
    

    I hope it will help you