Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FlatList onEndReached called On Load (React Native)

When I use onEndReached function in FlatList, it gets called automatically.

Below is the link of this issue.

Link

Is there a solution available for it or any alternative in iOS?

Edited:

Below is the code I tried but this doesn't seems to work.

constructor(props){
        super(props);
        this.state = {
            flatListReady:false
        }
    }

    loadMore(){
        if(!this.state.flatListReady){
            return null;
        }
        else{
            alert("End Reached")
        }
    }

    _scrolled(){
        this.setState({flatListReady:true});
    }

    render() {
        return (
            <Layout style={{ flex: 1 }}>

                <FlatList
                    data={listData}
                    renderItem={({item}) => this._renderItem(item)}
                    keyExtractor={(item, index) => item.key}
                    onEndReached={() => this.loadMore()}
                    onEndReachedThreshold={0.5}
                    onScroll={() => this._scrolled()}
                />

            </Layout>
like image 482
Shubham Bisht Avatar asked Jul 15 '26 04:07

Shubham Bisht


2 Answers

Try this,

onEndReachedThreshold={0.5}
onEndReached={({ distanceFromEnd }) => {
if(distanceFromEnd >= 0) {
     //Call pagination function
}
}}
like image 192
Gokul Kulkarni Avatar answered Jul 22 '26 20:07

Gokul Kulkarni


Sometimes things don't work like they are supposed to, at the end of the day it's not native code where, so may the order of your components or the fact that the Flatlist is encapsulated in a component that is not intended to be, or there is some property should be passed to the Flatlist component itself to activate the onEndReached callback properly.

I've faced this myself, and I didn't know what to do to make it work properly.

A beautiful workaround is derived from the fact the Flatlist inherits ScorllView properties. so you could use the onScroll property to detect if the end has reached or not.

<FlatList
    data={this.props.dashboard.toPreviewComplaints}
    onScroll={({nativeEvent})=>{
        //console.log(nativeEvent);
        if(!this.scrollToEndNotified && this.isCloseToBottom(nativeEvent)){
             this.scrollToEndNotified = true;
             this.loadMoreData();
        }
    }}
/>

this.scrollToEndNotified is used as a flag not to abuse the call to the loadMore endpoint

isCloseToBottom({layoutMeasurement, contentOffset, contentSize}){
    return layoutMeasurement.height + contentOffset.y >= contentSize.height - 100;
}

So whenever it succeed in the isCloseToBottom call it means that you have reached the end of the list, so you can call the loadMoreData function

like image 20
Abdurhman An-naggar Avatar answered Jul 22 '26 20:07

Abdurhman An-naggar