javascript - How can I fetch data from mongoDB and display it on react front end - Stack Overflow

I am new to MERN and I am learning it. I don't know how to fetch all the data from a specific coll

I am new to MERN and I am learning it. I don't know how to fetch all the data from a specific collection and display the data of each record on separate cards. I have developed the backend code and is working perfectly when I send requests via postman but fetching and displaying data from React app is a problem for me. How can I do that?

My Backend API code

router.get('/ads', async (req,res,next)=>{
  try{
    const ads = await Ads.find();

    return res.status(200).json({
      success: true,
      count: ads.length,
      data: ads,
    });
  } catch(err) {
    console.log(err);
    res.status(500).json({ error: 'server error' });
  }
});

I am new to MERN and I am learning it. I don't know how to fetch all the data from a specific collection and display the data of each record on separate cards. I have developed the backend code and is working perfectly when I send requests via postman but fetching and displaying data from React app is a problem for me. How can I do that?

My Backend API code

router.get('/ads', async (req,res,next)=>{
  try{
    const ads = await Ads.find();

    return res.status(200).json({
      success: true,
      count: ads.length,
      data: ads,
    });
  } catch(err) {
    console.log(err);
    res.status(500).json({ error: 'server error' });
  }
});

Share Improve this question edited Dec 2, 2021 at 20:43 Parzh 9,9434 gold badges46 silver badges80 bronze badges asked Dec 2, 2021 at 16:51 AHMAD IRSHADAHMAD IRSHAD 1191 gold badge2 silver badges10 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 1

Just use the AXIOS library to do your REST calls in the front-end. What you created in your nodejs project is just an endpoint, now you will have to make an API call to the endpoint from the front end.

Answer by Heartbit is also apt, but typically in React, devs use the AXIOS library for the rest API calls.

Read the docs here: https://www.npmjs./package/axios

As you are starting watch a tutorial on AXIOS if the documentation is too much for you.

After importing Axios, inside useEffect hook, you should be writing something like this:

axios.get('/ads')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

There are many ways that you can query to get data from your API server. so here I am trying to describe two of them.

1. By native browser Fetch API:


const AdsContainer = ({children}) => {
  const [data, setData] = useState();

  useEffect(() => {
    fetch('/ads').then(response => {
      setData(response.json())
    })
  }, [])

  return (
    <AdsComponent data={data}>
      {children}
    </AdsComponent>
  )
}

2. by react-query:

This will give you more synchronized handling like loading, Error, Caching, and more.

First, at the top level of your app, you should provide it.

import { QueryClient, QueryClientProvider } from "react-query";
import AdsContainer from "./AdsContainer";

const queryClient = new QueryClient()
function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <div className="App">
        <AdsContainer />
      </div>
    </QueryClientProvider>
  );
}

Then your AdsContainer could fetch data as bellow:

import {useQuery} from "react-query";

const AdsContainer = ({children}) => {
  const query = useQuery('todos', () => {
    return fetch("/ads").then(response => {
      return response.json()
    })
  })

  
  /* logics that depends on your data
   * userEffect(() => {}, [data.length])
   */

  return (
    <AdsComponent data={query.data}>
      {children}
    </AdsComponent>
  )
}

I remend you install axios.

  • Learn more https://www.npmjs./package/axios
  • Using:
useEffect(() => {
  const getAds = async () => {
    const res = await axios.get('/ads')
    console.log(res.data)
  }
  getAds()
}, [])

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744326461a4568672.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信