'Trying to display MongoDB documents content on my front end

I am currently struggling displaying the contents of my database in my front end components. I am using the MERN stack to create a grocery list app and so far, I have a form with an onsubmit event in my front end that is sending data to MongoDB and saving it. I see what I am submitting in my database without a problem.

To display the data I have created a backend route where I find the list in my database backend route image

then I make an api to that backend route via a gentlest action I create getlist api action

I try calling his action in my front end component but all I see is an empty array in my console not a populated list of any sort. In the past I make the api call then set the state of whatever I need to set and map through that to display it . Let me know if you guys have any ideas

frontend component to show the list



Solution 1:[1]

Usually the way you communicate with your backend api is by performing a request via axios or fetch.

If you use axios then create a function and perform a post request to your backend route inside it. Then call that function inside useEffect.

If you are using redux then simply call the action inside useEffect.

Edit: Let's assume that your server is listening to port 8000 for this example `

 const [groceryList, setGroceryList] = useState([]);

 async function fetchData() {
 const result = await axios.get(`/http://localhost:8000/getList`);
 setGroceryList(result);
  }

 useEffect(() => {
 fetchData()
 },[])

`

Solution 2:[2]

All You Need To Do:


import {useEffect,useState } from "react";
 
//use it inside your function component in JS file and make sure your //server 3001 is runing by using express
function abcd(){

const [object, setObj] = useState([
    {
      title: "",
      description: "",
      url: "",
    },
  ]);

  useEffect(() => {
    fetch("http://localhost:3001/pages")
      .then((res) => res.json())
      .then((jsonRes) => setObj(jsonRes));
  }, []);


//Render

return(
 <div
        style={{
          display: "flex",
          flexDirection: "column",
          width: "20%",
          margin: "auto auto",
        }}
      >
        {object
          .sort((a, b) => {
            var titleA = a.title;
            var titleB = b.title;
            if (titleA < titleB) {
              return -1;
            }
            if (titleA > titleB) {
              return 1;
            }
            return 0;
          })
          .map((Ob) => {
            return (
              <img
                key={Ob.title}
                src={Ob.url}
                alt={Ob.description}
                name={Ob.title}
                onClick={handleClick}
              ></img>
            );
          })}
      </div>)
}

//Use the below code in your BackEnd in order to fetch all the data from the //MongoBackEnd(Express)
//Use your MongoDB server address and mongoSchema and store it in a //Variable("Handle")

const Handle = require("./views/mongoschema");

  app.get("/pages", (req, res) => {
      Handle.find({})
        .then((items) => res.json(items))
        .catch((err) => console.log(err));
    });

By doing the above things you can fetch all the MongoDB data in the frontEnd and add designs or Templates to it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 ABHI SHEK