0

I am trying to return a String value to display it in my HTML. In my HTML, I'm using a Text element in a View (similar to a div in React Native) and try to fill it with that that I'm getting from the method _getCategories. The problem is that I can't make the method return a String value, since the value is returned inside a Promise.

Now, I'm trying to make this method return a simple String value:

    _getCategories = item => {
    const categoryNames = [];
    let fetches = [];
    var allCategories = '';
    for (var i = 0; i < item.categories.length; i++) {
      allCategories = allCategories + item.categories[i] + ',';
    }
    allCategories = allCategories.substring(0, allCategories.length - 1);
    fetches.push(
      fetch(
        'http://54.168.73.151/wp-json/wp/v2/categories?include=' + allCategories
      ).then(response =>
        response.json().then(responseJson => {
          var names = '';
          for (let category of responseJson) {
            names = names + category.name + ', ';
          }
          this.names = String(names.substring(0, names.length - 2));
          console.log(this.names);
          return <Text style={styles.categories}>{this.names}</Text>;
        })
      )
    );
  };

I thought this returns the correct value already, but it's not showing in my View. I call the method above as follows:

<View>
      {this._getCategories(item)} //this will be a text element after return
</View>

The issue can be reproduced here:

Reproducible version

MJM
  • 141
  • 1
  • 2
  • 11
  • `_getCategories` **can't** return its result, because it returns before it has the result value. It will have to return a *promise* of the result. You haven't said what framework you're using, but it looks like React. If so, you'd typically do this either in the parent component (passing the result as a prop) or you ensure that `render` knows how to render without it, and you start this process in [`componentDidMount`](https://reactjs.org/docs/react-component.html#componentdidmount), setting state (which will trigger re-rendering) when you have the result. – T.J. Crowder Oct 06 '18 at 15:37
  • I'm pass the result as a prop, but I fail to do so, because the parent component only renders other attributes. I added a link to the code above (the class is named GenresScreen). Could you give me a suggestion about how to do in my situation? – MJM Oct 06 '18 at 16:23

0 Answers0