Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using FlatList#onViewableItemsChanged to call a Component function

I'm currently attempting to implement a form of LazyLoading using the FlatList component, which introduces a neat little feature called onViewableItemsChanged which gives you a list of all of the components that are no longer on the screen as well as items that are now on the screen.

This is a custom LazyLoad implementation and as such is more complicated than most LazyLoad open-sourced libraries that are available, which is why I'm working on my own implementation. I'm already looked into react-native-lazy-load and others.

Basically, I need to be able to call a function that's part of the component being rendered in the FlatList, I've tried creating a reference to the item rendered in the FlatList and calling it as such, but it doesn't seem to work.

For example:

<FlatList data={...}
    renderItem={(item) => <Example ref={(ref) => this[`swiperRef_${item.key}`] = ref}}
    onViewableItemsChanged={this.onViewableItemsChanged}
/>

onViewableItemsChanged = ({viewableItems}) => {
    viewableItems.forEach((item) => {
        const { isViewable, key } = item;
        if(isViewable && !this.cachedKeys.includes(key)) {
            const ref = this[`swiperRef_${key}`];
            if(!ref) return console.error('Ref not found');
            ref.startLoading();
            this.cachedKeys.push(key);
        }
    });
}

Now in the <Example /> component I would have a function called startLoading which should be called when a new visible item is brought onto the screen, however the ref never exists.

like image 505
Christian Tucker Avatar asked Jul 21 '17 18:07

Christian Tucker


1 Answers

I was actually doing everything correctly, but I accidently forgot to deconstruct the parameter returned from the renderItem function, so (item) should have been ({ item })

That's all there was to it.

like image 120
Christian Tucker Avatar answered Oct 13 '22 21:10

Christian Tucker