Lucas Veiga
Lucas Veiga

Reputation: 1795

React Native: Render on Fetch

I'm currently learning react & react-native. I imported a image slider on my project and includes it on my Component as this:

render() {
    return (
          <TopScreen style={styles.viewpager}/>
    );
  }

On this image slider, I fetch images from my json endpoint and populates it. It's working fine. But what I want is to understand, how can I place a 'loading' text or a spinner on this while it's loading.

I tried to check if my banners_top has already loaded on the render() function, but it only renders the slider when it's loaded.

On my image slider js, I currently have this:

var TopScreen = React.createClass({

  componentWillMount : function () {

      fetch('http://example.org/myendpoint')
        .then((response) => response.json())
        .then((responseJson) => {

          var data = responseJson.top;
          var dataSource = new ViewPager.DataSource({
            pageHasChanged: (p1, p2) => p1 !== p2,
          });

          var setIt = dataSource.cloneWithPages(data);

          this.setState({banners_top : setIt});

        })
        .catch((error) => {
          console.error(error);
        });
  },

  getInitialState: function() {
    return {
      banners_top: null
    };
  },

  render: function() {

    if(!this.state.banners_top) {
      return (
        <View>
          <Text>lucas!</Text>
        </View>
      );
    }
   else {
      return (
          <ViewPager
            style={this.props.style}
            dataSource={this.state.banners_top}
            renderPage={this._renderPage}/>
      );
    } 



  },

  _renderPage: function(
    data: Object,
    pageID: number | string,) {
    return (
      <Image
        source={{uri: data.banner.image}}
        style={styles.page} />
    );
  },
});

var styles = StyleSheet.create({
  page: {
    width: deviceWidth,
    height: 240,
    resizeMode: 'contain'
  },
});

Thanks!

Upvotes: 1

Views: 4396

Answers (1)

Jakkra
Jakkra

Reputation: 651

setState will make the app re render the view. Like this:

componentWillMount() {
    this.setState({ showLoading: true});

    fetch('http://someUrl.com/api/xxx')
    .then(result.json())
    .then((json) => {
        this.setState({ showLoading: false });
        ... 
        }
    })
}
render() {
    if(this.state.showLoading === true) {
        render your header/spinner...
    }
    ...
}

However, you might want to look into Redux, it's a nice way to handle stuff like this a little more elegant, plus it has other nice features. Read about redux her

Upvotes: 2

Related Questions