How to use cacheImages for FlatList


#1

I built images gallery by FlatList in my app, like this, it depends on a “react-native-img-cache” module.
In expo, I’m trying to build it like this:

...

async _loadAssetsAsync() {
        let assets = [], i;
        for (i = 0; i < this.props.data.length; i++) {
            assets.push(this.props.data[i].key);
        }

        const imageAssets = cacheImages(assets);

        await Promise.all([
            ...imageAssets
        ]);

        this.setState({appIsReady: true});
    }

    ......
    
    <FlatList
                contentContainerStyle={styles.container}
                data = {this.props.data}
                renderItem={({item}) =>
                    <TouchableOpacity>
                        <Image
                            source={{uri: item.key}}
                            style={styles.containerImage}
                        />
                    </TouchableOpacity>
                }

    ....
   />

It seems images have not been cached, what is the correct way to build this?

Thanks!


#2

What does cacheImage do? It looks like react-native-img-cache won’t work with Expo since it depends on some native code, but we already have image caching utilities built in. Have you looked at this https://docs.expo.io/versions/latest/guides/preloading-and-caching-assets.html?