-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?

1
  • 1
    how are you rendering it Commented Mar 25, 2018 at 17:07

1 Answer 1

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>
  );
}
Sign up to request clarification or add additional context in comments.

1 Comment

There is no reason to answer this question. It should be marked as a duplicate. This exact question has been answered 100s of times.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.