Home > Software engineering >  React Native Image Render Flatlist and Use State hook
React Native Image Render Flatlist and Use State hook

Time:09-29

I have a screen in my ap, that's users upload photos. In this screen, photo can be selected from gallery or taken from camera. I have an array state where I keep the uri of photos. I show the photos in flatlist with this array state. Next to each photo there is an icon to delete. But the function called by this icon does not update the array state and delete the photo. Probably state updates asynchronously. Please help me!

const [images, setImages] = useState([]); //images array
const selectFile = async() => { //image from gallery
        await launchImageLibrary(options, res => {
            console.log('Response = ', res);
            if (res.didCancel) {
                console.log('User cancelled image picker');
            }else {
               let source = res;
               setImages(prevImages=>([...images,source.assets[0].uri]));
               console.log(images);
            }
        });
};
const takePicture = async () => { //take picture save cameraroll and get picture
        try {
            const options = {quality: 0.5, base64: false};
            let imageUri;
            const imageData = await camera.takePictureAsync(options).then(data => {
                imageUri=data.uri;
            });
            await CameraRoll.save(imageUri, {type: 'photo'});
            CameraRoll.getPhotos({
                first:1,
                assetType: 'Photos',
            }).then((r)=>{
                let imageUri=r.edges[0].node.image.uri;
                setImages([...images,imageUri]);
            });
            console.log(images);
        }catch (e) {
            console.log(e);
        }
};
const removeImage=async(item)=>{ //delete function
        setImages(prevImages=>([...prevImages,images.filter(x=>x!==item)]));
        alert(images);
}
return(
<FlatList
    data={images}
    keyExtractor={(item,index)=>item}
    numColumns={2}
    renderItem={({item,index})=>{
      return (
         <View style={{margin:2, borderWidth:2, borderColor:'rgba(255,255,255,0.42)',shadowColor: 'black',
               shadowOpacity: 0.25,
               shadowOffset: {width: 0, height: 2},
               shadowRadius: 8,
               overflow: Platform.OS === 'android' ? 'hidden' : 'visible',width:160,height:165,backgroundColor:'transparent'}}>
                   <Image
                        resizeMode="cover"
                        style={{
                             flex:1,
                        }}
                        source={{uri: item}}
                   />
                   <TouchableOpacity
                       key={index}
                       underlayColor='transparent'
                       onPress={()=>removeImage(item)}
                   >
                      <AntDesign name={'minuscircle'} size={24} color={Colors.molekulRed} style={{marginLeft:'85%', marginTop:'-100%'}}/>
                   </TouchableOpacity>
         </View>

    }}
/>

)

CodePudding user response:

try this,

const removeImage=async(item)=>{ //delete function
        setImages(prevImages=>([...prevImages.filter(x=>x!==item)]));
        alert(images);
}
  • Related