-2

I have the following code which works perfectly on a list of objects assigned to a const. But whenever I take the list of objects from a DRF API endpoint, I can console.log the objects, but cannot display information from the objects to the site. Here is the code that I use.

    const comps = []
    axios.get('http://127.0.0.1:8000/')
      .then(response => {
        const items = response.data;
        items.forEach((item) => {
          console.log(item)
          comps.push(<Item
                        id={item.id}
                        name={item.name}
                        inCart={this.state.cart[item.id]}
                        quantity={item.quantity}
                        unit={item.unit}
                        price={item.price}
                        handleDecreaseClick={handleDecreaseClick(item.id, item.price)}
                        handleIncreaseClick={handleIncreaseClick(item.id, item.price)}
                        key={item.id} />)
        })
      })
      .catch(function(error) {
        console.log(error);
      });

I know the loop is working perfectly because I can log the objects in the browser console.

enter image description here

But nothing is shown in the site. What could possibly be the problem?

MiniGunnR
  • 5,590
  • 8
  • 42
  • 66

1 Answers1

2

If you are doing this in within render() function, move the async request part to componentDidMount().

componentDidMount() {

  axios.get('http://127.0.0.1:8000/')
    .then((response) => {
      this.setState({items: response.data});
}

render() {
  return (
    <div>
      { this.state.items.map((item) => (
        <Item
          id={item.id}
          name={item.name}
          inCart={this.state.cart[item.id]}
          quantity={item.quantity}
          unit={item.unit}
          price={item.price}
          handleDecreaseClick={handleDecreaseClick(item.id, item.price)}
          handleIncreaseClick={handleIncreaseClick(item.id, item.price)}
          key={item.id}
        />
      )) }
    </div>
  );
}
Eric
  • 2,635
  • 6
  • 26
  • 66
  • There is no reason to answer this question. It should be marked as a duplicate. This exact question has been answered 100s of times. – Aaron Rumery Mar 25 '18 at 17:15