Home > database >  Fetch Data from mongoDb using ReactJs and node
Fetch Data from mongoDb using ReactJs and node

Time:11-06

I have a mern project where i want to fetch data from mongodb in my reactjs.

I have gone through sevral previous question but it didn't help!

i have successfully fetched all data all together

But i want to fetch olny specific data ilke email. How can i do that?

Admin.js(frontend)


import React from 'react';
import axios from 'axios';

class Admin extends React.Component {
  state = {
    phone: '',
    email: '',
    posts: []
  };

  // componentDidMount = () => {
  //   this.getBlogPost();
  // };

  hello = () => {
    axios.get('/getuser')
      .then((response) => {
        const data = response.data;
        this.setState({ posts: data });
        console.log(data);
      })
      .catch(() => {
        alert('Error retrieving data!!!');
      });
  }

  displayBlogPost = (posts) => {

    if (!posts.length) return null;

    return posts.map((post, index) => (
      <div key={index} className="blog-post__display">
        <h3>{post.phone}</h3>
        <p>{post.email}</p>
      </div>
    ));
  };


  render() {
    return (
      <>
        <h1>
          <button onClick={this.hello} class="btn btn-danger">click here to get data</button>
        </h1>

        <div className="blog-">
          {this.displayBlogPost(this.state.posts)}
          <table>
            <tr>
              <th>email</th>
              <th>phone</th>
            </tr>
            <tr>
              <td>[email protected]</td>
              <td>8340251638</td>
            </tr>
            <tr>
              <td>[email protected]</td>
              <td>78750251638</td>
            </tr>
            <tr>
              <td>[email protected]</td>
              <td>9652251638</td>
            </tr>
          </table>
        </div>       
      </>
    )
  }
}


export default Admin;

i am getting data in my browser like this---

image of my browser

How can i show olny specific data

thankyou

CodePudding user response:

So I am going to assume you have an Express App running with endpoints you are calling from this front-end code given the /get-user endpoint. The endpoint returns all of the user data for one or more users depending on how you set it up. In order to get a list emails for users, you will need something to distinguish your API call to the Express App that you want only the emails for the users, and not the full user object. There are a lot of ways to make this distinction, but another route is probably the best option to adhere to REST in some way. Below is a possible example:

Express Endpoint
app.get('/users/email', (req, res) => { 
   Call MongoDB and filter the user list to just email for response 
}

REACT Call
emails = () => {
    axios.get('/users/email')
      .then((response) => {
        const data = response.data;
        this.setState({ emails: data });
        console.log(data);
      })
      .catch(() => {
        alert('Error retrieving data!!!');
      });
  }

It is in the Express app that you should filter and ideally sort data for the front-end app to consume. Otherwise you risk sending too much data to the front-end or sending sensitive data by accident. Take a look at the below link for a bit more robust example.

https://codingthesmartway.com/the-mern-stack-tutorial-building-a-react-crud-application-from-start-to-finish-part-1/

  • Related