score:0

Accepted answer

This code will handle the object that is returned by api and also moves the fetching to componentDidMount.

constructor(props) {
   super(props);
   this.state = {
      data: [],
   }
}
componentDidMount() {
    firebaseCon.content.get('text', { fields: ['id', 'title'] })
      .then((response) => {
          let data = [];
          for (item in response) {
              data.push(response[item]);
          }
          this.setState({ data });
      });
}

render() {
    let itemList = this.state.data.map(function(item) {
        return <li className="item" key={item.id}>{item.title}</li>;
    });
    return (
        <ul>
            {itemList}
        </ul>
    )
}

A closer look at Promises' methods then and catch should make it clearer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

score:-1

Have you seen this?

https://github.com/axios/axios

Promise based HTTP client for the browser and node.js.

You can see it in action in this tutorial, used with React:

https://codeburst.io/building-appointment-scheduler-app-in-react-and-nodejs-f163c4eaab6b

Hope it helps.

score:6

First of all, I would say that you are doing in wrong way.

You should never make a server request in render function.

You should make a server request in componentWillMount() or componentDidMount().

If you know async/await concept then it would be helpful for you.

You can check this link..

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

You can try like this one...

import React, { Component } from 'react';
export default class ListData extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: []
    };
  }
  async componentDidMount() {
    const data = await firebaseCon.content.get('text', { fields: ['id', 'title'] });
    this.setState({ data });
  }

  render() {
    const { data } = this.state;
    const itemList = data.map(function(item) {
            return <li className="item" key={item.id}>{item.title}</li>;
        });
    return (
      <div>
        {data.length > 0 &&
           <ul>
             { itemList }
           </ul>
        }
      </div>
    );
  }

}

Hope it will be help


Related Query

More Query from same tag