1

I have a FlatList which has the following code snippet

            <FlatList
               ...........
                refreshing={this.state.refresh}
                onRefresh={() => {
                    this.setState({
                        refresh: true
                    });
                    console.log("DEBUG refresh call state=" + this.state.refresh);
                    this._fetchArticles();
                }}

                onEndReached={() => {
                    console.log("DEBUG end reached make a network call");
                    this.setState({
                        refresh: false,
                        showLoadingBottom: true
                    });
                    this._fetchArticles();
                }}
              ...........
            />

The problem is even though i update the refresh variable value in the state, the value does not update in the debug statements that I am printing above, neither does it show the latest state value for refresh variable in the _fetchArticles function. I am not sure if i have does it wrong or if the setState is an async call, if so how to I handle fetching new data since, should i maintain a non-state variable instead since that would instantly refresh.

Jude Fernandes
  • 7,437
  • 11
  • 53
  • 90

1 Answers1

0

The setState callback will execute your log statement after the state has been set since state is not set instantly and is indeed an async op.

this.setState({
    refresh: true
}, () => {
    console.log("DEBUG refresh call state=" + this.state.refresh);
});
danday74
  • 52,471
  • 49
  • 232
  • 283