My fairly basic react native project uses expo-media-library to retrieve some photographs from a users photo album, presenting them in a stack of cards - kinda similar to Tinder. My code generally works, however instead of just displaying the top photo/card, several others are displayed in the first few seconds and I can't figure out why. I think it has to do with the size of the images and the delay in loading them but I'm not sure. I'd really appreciate advice about how to fix this.
Here's what's happening:
As you can see, instead of displaying the first image on the stack, another image is displayed briefly first even though I have not coded for this to happen.
Here is my code (leaving out imports and styles):
const ImageStack = ({navigation, route}) => {
const [status, requestPermission] = MediaLibrary.usePermissions()
const [photos, setPhotos] = useState([]) //where we store stack of cards
const [isLoading, setIsLoading]=useState(true) //only displaying stack when images have loaded
// On load, retrieve photos from gallery
useEffect(async()=>{
const getPhotos = await getAllPhotos(route.params.id)//id for the album is passed to component
setPhotos(getPhotos)
setIsLoading(false) // only when photos have been retrieved should they be displayed
},[])
// function to retrieve photos from gallery
const getAllPhotos = async (id) => {
let album = await MediaLibrary.getAssetsAsync({album: id, mediaType: 'photo', first: 20, sortBy: ['creationTime']})
const foundPhotos = album['assets']
const updatedPhotos = []
for (let i=0;i<foundPhotos.length;i++){
const updatedPhoto = await MediaLibrary.getAssetInfoAsync(foundPhotos[i].id)
updatedPhotos.push({
uri: updatedPhoto['localUri'],
id: updatedPhoto['id']
})
}
return updatedPhotos
}
const renderCards = () => {
return photos.map((item, i)=>{
return(
<Animated.View key={item.id} style={{height: SCREEN_HEIGHT -120, width: SCREEN_WIDTH, padding: 10, position: 'absolute'}}>
<Image source={{uri: item.uri}} style={{flex: 1, height: null, width: null, resizeMode: 'cover', borderRadius: 20}}/>
</Animated.View>
)
})
}
return (
<View style={{flex:1}}>
<View style={{height:60}}>
</View>
<View style={{flex:1}}>
{!isLoading && renderCards()} //Only render the photo cards when loaded
</View>
<View style={{height:60}}>
</View>
</View>
Any suggestion how to fix this? Thanks!
Fixed this. So the issue was the size of the images. I added image compression which completely fixed the problem:
const compressedImage = await ImageManipulator.manipulateAsync(updatedPhoto.localUri, [], { compress: 0.2 });