最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to display data coming from mongodb to reactjs after clicking the button? - Stack Overflow

programmeradmin0浏览0评论

I am making react project using express.js, mongodb, react.js, and node.js. and trying to fetch data from backend api which is running on port 5000.

When I check the api using postman, it is working. And the data is showing in the browser's console. Also, when I press Get button as given in the code below, it doesn't work on the browser. But I'm able to see the array data in the browser's console.

<Button onClick={()=><li>{employeeItem}</li>}>Get</Button>

Here is my full code:

import React, { Component } from "react";
import {
  form,
  FormGroup,
  FormControl,
  ControlLabel,
  Button
} from "react-bootstrap";
import "./App.css";
import { stringify } from "querystring";

class App extends Component {
  constructor(props) {
    super(props);

    this.AddName = this.AddName.bind(this);
    this.AddContact = this.AddContact.bind(this);
    this.AddAge = this.AddAge.bind(this);

    this.state = {
      name: "",
      contact: "",
      age: "",
      employees: []
    };
  }
  AddName(e) {
    this.setState({ name: e.target.value });
  }
  AddContact(e) {
    this.setState({ contact: e.target.value });
  }
  AddAge(e) {
    this.setState({ age: e.target.value });
  }

  ponentWillMount() {
    fetch("http://localhost:5000/api/employees")
      .then(res => res.json())
      .then(data => this.setState({ employees: data }));
  }

  render() {
    const employeeItem = this.state.employees.map(employee => (
      <div key={employee._id}>
        <h3>{employee.name}</h3>
        <p>{employee.contact}</p>
        <p>{employee.age}</p>
      </div>
    ));
    return (
      <div className="App">
        <header className="App-header">
          <h1 className="App-title">Employee List</h1>
        </header>
        <div className="Layout">
          <form>
            <FormGroup>
              <ControlLabel>Name:</ControlLabel>
              <FormControl
                type="text"
                value={this.state.name}
                placeholder="Employee name"
                onChange={this.AddName}
              />
              <div>
                <ControlLabel>Contact:</ControlLabel>
                <FormControl
                  type="number"
                  value={this.state.contact}
                  placeholder="Mobile number"
                  onChange={this.AddContact}
                />
              </div>
              <div>
                <ControlLabel>Age:</ControlLabel>
                <FormControl
                  type="number"
                  value={this.state.age}
                  placeholder="Age"
                  onChange={this.AddAge}
                />
              </div>
            </FormGroup>
            <Button type="submit">Add</Button>
            <Button onClick={() => console.log({ employeeItem })}>Get</Button>
            <Button type="submit">Delete</Button>
          </form>
        </div>
      </div>
    );
  }
}

export default App;

on running page

I am making react project using express.js, mongodb, react.js, and node.js. and trying to fetch data from backend api which is running on port 5000.

When I check the api using postman, it is working. And the data is showing in the browser's console. Also, when I press Get button as given in the code below, it doesn't work on the browser. But I'm able to see the array data in the browser's console.

<Button onClick={()=><li>{employeeItem}</li>}>Get</Button>

Here is my full code:

import React, { Component } from "react";
import {
  form,
  FormGroup,
  FormControl,
  ControlLabel,
  Button
} from "react-bootstrap";
import "./App.css";
import { stringify } from "querystring";

class App extends Component {
  constructor(props) {
    super(props);

    this.AddName = this.AddName.bind(this);
    this.AddContact = this.AddContact.bind(this);
    this.AddAge = this.AddAge.bind(this);

    this.state = {
      name: "",
      contact: "",
      age: "",
      employees: []
    };
  }
  AddName(e) {
    this.setState({ name: e.target.value });
  }
  AddContact(e) {
    this.setState({ contact: e.target.value });
  }
  AddAge(e) {
    this.setState({ age: e.target.value });
  }

  ponentWillMount() {
    fetch("http://localhost:5000/api/employees")
      .then(res => res.json())
      .then(data => this.setState({ employees: data }));
  }

  render() {
    const employeeItem = this.state.employees.map(employee => (
      <div key={employee._id}>
        <h3>{employee.name}</h3>
        <p>{employee.contact}</p>
        <p>{employee.age}</p>
      </div>
    ));
    return (
      <div className="App">
        <header className="App-header">
          <h1 className="App-title">Employee List</h1>
        </header>
        <div className="Layout">
          <form>
            <FormGroup>
              <ControlLabel>Name:</ControlLabel>
              <FormControl
                type="text"
                value={this.state.name}
                placeholder="Employee name"
                onChange={this.AddName}
              />
              <div>
                <ControlLabel>Contact:</ControlLabel>
                <FormControl
                  type="number"
                  value={this.state.contact}
                  placeholder="Mobile number"
                  onChange={this.AddContact}
                />
              </div>
              <div>
                <ControlLabel>Age:</ControlLabel>
                <FormControl
                  type="number"
                  value={this.state.age}
                  placeholder="Age"
                  onChange={this.AddAge}
                />
              </div>
            </FormGroup>
            <Button type="submit">Add</Button>
            <Button onClick={() => console.log({ employeeItem })}>Get</Button>
            <Button type="submit">Delete</Button>
          </form>
        </div>
      </div>
    );
  }
}

export default App;

on running page

Share Improve this question edited Sep 9, 2018 at 22:21 Ashutosh 5187 silver badges21 bronze badges asked Sep 9, 2018 at 22:10 ManishManish 3931 gold badge6 silver badges20 bronze badges 3
  • What do you mean it is not working? Can you give us a minimal code example? Where is the part you actually query your backend? – Almaju Commented Sep 9, 2018 at 22:15
  • @Almaju I am trying to display the data ing from my database to my page on pressing Get button but is not working. I have shared the screen shot also. When i press Get button the data is ing on the console but i wanted that data to e on my page. – Manish Commented Sep 9, 2018 at 22:27
  • 1 You can't render the items like you are trying inside a button callback. Where do you want to see those items and when? You are already fetching the data and set your state. Don't you want to see them immediately after the fetch? You can do it with a button of course with 2 options: 1. Trigger the fetch with the button instead of doing it in ponentWillMount then show items. 2. Pre-fetch but hide the items with a suitable state property. Then change it with the button click. – devserkan Commented Sep 9, 2018 at 23:03
Add a ment  | 

1 Answer 1

Reset to default 5

You can't render an item as you are trying inside an onClick callback. You can render the items immediately after fetched them or you can trigger with an onClick the fetch or you can hide and show the items.

Immediately rendering

const employees = [
  { _id: 1, name: "foo", contact: "abc", age: 20 },
  { _id: 2, name: "bar", contact: "efg", age: 30 },
  { _id: 3, name: "baz", contact: "hij", age: 40 }
];

const fakeRequest = () =>
  new Promise(resolve => setTimeout(() => resolve(employees), 1000));

class App extends React.Component {
  state = {
    employees: []
  };

  ponentDidMount() {
    fakeRequest().then(employees => this.setState({ employees }));
  }

  render() {
    const employees = this.state.employees.map(employee => (
      <div style={{ border: "1px solid black" }} key={employee._id}>
        <h3>Name: {employee.name}</h3>
        <p>Contact: {employee.contact}</p>
        <p>{employee.age}</p>
      </div>
    ));

    return (
      <div>
        <p>Data will be fetched in a second automatically.</p>
        {employees}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Get with a button click

const employees = [
  { _id: 1, name: "foo", contact: "abc", age: 20 },
  { _id: 2, name: "bar", contact: "efg", age: 30 },
  { _id: 3, name: "baz", contact: "hij", age: 40 },
];

const fakeRequest = () => new Promise( resolve =>
  setTimeout( () => resolve( employees ), 1000)
);

class App extends React.Component {
  state = {
    employees: [],
  };

  getEmployees = () =>
    fakeRequest()
      .then(employees => this.setState({ employees }))

  render() {
    const employees = this.state.employees.map(employee => (
      <div style={{ border: "1px solid black"}} key={employee._id}>
        <h3>Name: {employee.name}</h3>
        <p>Contact: {employee.contact}</p>
        <p>{employee.age}</p>
      </div>
    ));

    return (
      <div>
      <p>Data will be fetched after the button click.</p>
      <button onClick={this.getEmployees} >Get Employees</button>
      {employees}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Show/hide method

const employees = [
  { _id: 1, name: "foo", contact: "abc", age: 20 },
  { _id: 2, name: "bar", contact: "efg", age: 30 },
  { _id: 3, name: "baz", contact: "hij", age: 40 },
];

const fakeRequest = () => new Promise( resolve =>
  setTimeout( () => resolve( employees ), 1000)
);

class App extends React.Component {
  state = {
    employees: [],
    showEmployees: false,
  };
    
  ponentDidMount() {
    fakeRequest()
      .then(employees => this.setState({ employees }))
  }

  toggleEmployees = () => this.setState( prevState => ({
    showEmployees: !prevState.showEmployees,
  }))

  render() {
    const { showEmployees } = this.state;
    const employees = this.state.employees.map(employee => (
      <div style={{ border: "1px solid black"}} key={employee._id}>
        <h3>Name: {employee.name}</h3>
        <p>Contact: {employee.contact}</p>
        <p>{employee.age}</p>
      </div>
    ));

    return (
      <div>
      <p>Data will be fethced automatically in a second but will be hidden by default. Button click toggles this state.</p>
      <button
        onClick={this.toggleEmployees}
      >
        {
          showEmployees ? "Hide Employees" : "Show Employees"
        }
      </button>
      {this.state.showEmployees && employees}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

发布评论

评论列表(0)

  1. 暂无评论