1

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 });
  }

  componentWillMount() {
    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

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? Commented Sep 9, 2018 at 22:15
  • @Almaju I am trying to display the data coming 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 coming on the console but i wanted that data to come on my page. 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 componentWillMount then show items. 2. Pre-fetch but hide the items with a suitable state property. Then change it with the button click. Commented Sep 9, 2018 at 23:03

1 Answer 1

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: []
  };

  componentDidMount() {
    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.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/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.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/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,
  };
    
  componentDidMount() {
    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.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Sign up to request clarification or add additional context in comments.

3 Comments

This is great effort shown by you man. Keep up the great work. I hope the solution works for @manish
Thank you for the appreciation.
Big thanks, the solution you provided worked for me. Highly appreciate your effort.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.