DEV Community

Cover image for MERN CRUD(Read) - 7
Shubham Tiwari
Shubham Tiwari

Posted on

MERN CRUD(Read) - 7

Hello Guys today i am going to show you the "READ" opearation of Crud. I have already discussed "CREATE" opeartion in
https://dev.to/shubhamtiwari909/creating-express-server-6-9gf
Please check it out and other blogs of this series to understand everything clearly.

Lets get started...

Back-end

  • Open Backend Folder and open Queries.js file. You have already created a "post" method in the previous blog of this series so below that post method , write this code.

Queries.js

// get method
app.get("/", (req, res) => {
  const connnectToMongo = async () => {
    await mongo().then(async () => {
      try {
        const result = await userSchema.find({});
        res.send(result);
      } finally {
        console.log("Data Fetched succefully");
      }
    });
  };
  connnectToMongo();
});
Enter fullscreen mode Exit fullscreen mode
  • It will find all the records in the collection "users" and return the result as response to frontend.

Front-end

  • Open Frontend folder and then create a file a file named "DataView.js" inside components folder which is inside src folder and write this code

DataView.js

import React, { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { FcEditImage, FcDeleteDatabase } from 'react-icons/fc'
import axios from 'axios'

function Home(props) {

 const [data, setData] = useState([]);
 useEffect(() => {
    axios.get(`http://localhost:3001/`)
      .then((response) => {
        setData(response.data)
      })
      .catch((err) => console.log(err));
  }, [data])

return (
<div>
 <p className="my-4 text-3xl text-center">User Details</p>
      <div className="grid justify-content-center">
        <Link to='/add' className="btn btn-primary my-6 justify-self-center" >Add</Link>
        <div className="grid grid-cols-5 my-4 py-4 pl-2 bg-gradient-to-r from-black via-slate-800 to-slate-900
                rounded-lg">
          <h1>S No. </h1>
          <h1>Name</h1>
          <h1>Email</h1>
          <h1>Number</h1>
          <h1>Action</h1>
        </div>
        <div>
          {
            data?.map((contact, index) => {
              return (
                <div key={contact._id} className="grid grid-cols-5 gap-2 my-4 py-4 pl-2 bg-gradient-to-r from-purple-900 via-indigo-800 to-pink-900 
                rounded-lg">
                  <h1>{index + 1}.</h1>
                  <h1 className="capitalize">{contact.name}</h1>
                  <h1 className="break-words">{contact.email}</h1>
                  <h1>{contact.number}</h1>
                  <div className="space-x-3 flex flex-col md:block lg:block">
                    <Link className="btn btn-small mr-2">
                      <FcEditImage size="1.5rem" />
                    </Link>
                    <button className="btn btn-small">
                      <FcDeleteDatabase size="1.5rem" />
                    </button>
                  </div>
                </div>
              )
            })
          }
        </div>
      </div>
</div>
)
}
export default DataView
Enter fullscreen mode Exit fullscreen mode
  • We have used the useEffect hook and inside it used axios to fetch our data from backend and then using map method we have mapped the values to the html structure and it will create a separate box for every row of the data
  • We have also added two icons for update and delete method which we will cover later.
  • Now import this file in the App.js file and add it the routes

Home.js

import { Link, Routes, Route, useNavigate } from 'react-router-dom'
import Add from './components/Add'
import Home from './components/Home'
//added the dataview component
import DataView from './components/DataView'
.
.
.
.
.

{/*added it in the Links */}
<li className="nav-item">
   <Link to="/dataview" className="nav-link" aria-current="page">
     DataView
    </Link>
</li>
.
.
.
.
{/*added it in the Routes */}
<Route path='/dataview' element={<DataView />} />
.
.
.


export default App
Enter fullscreen mode Exit fullscreen mode
  • Now open 2 different terminal one for frontend and one for backend.
  • In one terminal navigate to the Backend folder using "cd Backend" and run this command "npm run dev" to start the express server.
  • In other terminal navigate to the frontend folder using "cd Frontend" and run this command "npm start" to start the React Js app.
  • Click the DataView link in the Navbar and Your data will be shown to the DataView page which is fetched from the backend.

NOTE - ADD SOME DATA TO THE MONGO DB DATA BASE EITHER USING MONGO DB ATLAS MANUALLY USING THE FORM WE HAVE CREATED TO SAVE THE DATA TO BACKEND.

Part - 1
https://dev.to/shubhamtiwari909/mern-crud-setup-148a

Part - 2
https://dev.to/shubhamtiwari909/2-mern-mongodb-setup-434g

Part - 3
https://dev.to/shubhamtiwari909/mongodb-connections-using-mongoose-3bl6

Part - 4
https://dev.to/shubhamtiwari909/mern-backend-modules-4-38pk

Part - 5
https://dev.to/shubhamtiwari909/mern-react-form-5-53ln

Part - 6
https://dev.to/shubhamtiwari909/creating-express-server-6-9gf

Thats it for this post, i will continue this series in the next blog where i will be creating the Express server and create the post method to get the data from our Form and save it in the mongo db database.
THANK YOU FOR READING THIS POST AND IF YOU FIND ANY MISTAKE OR WANTS TO GIVE ANY SUGGESTION , PLEASE MENTION IT IN THE COMMENT SECTION.
^^You can help me by some donation at the link below Thank you👇👇 ^^
☕ --> https://www.buymeacoffee.com/waaduheck <--

Also check these posts as well
https://dev.to/shubhamtiwari909/2-mern-mongodb-setup-434g

https://dev.to/shubhamtiwari909/mongodb-connections-using-mongoose-3bl6

https://dev.to/shubhamtiwari909/mern-backend-modules-4-38pk

Top comments (0)