0

I am having difficulty triggering the component refresh of Image in my react-native app while using a Flatlist and Context API

I have the following method for selecting an image and adding it to the context

`

const pickImage = async () => {      
    const context = useAppContext();
    const [images, setImages] = useState(context.appData?.images);
    
    await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    })
    .then(result => { if(!result.cancelled) { console.log(result); processImage(result); } })
    .catch(error => console.log(error));

    function processImage (image) {
        
       setImages([...images, image]);
       
      }
}

`

And this is my ImageView component that implements the Flatlist

`

export const ImageView = () => {
    const context = useAppContext();
    const [images, setImages] = useState(context.appData?.images);

    function removeImage() {
        console.log("Remove Image");
        const _images = context.appData?.images.filter(item => item != item);
        context.setImages(_images);
    }

    const renderItem = ({ item, index }) => {
        return (
        <View>
            <TouchableOpacity onPress={removeImage} style={{position: 'absolute', zIndex:3, elevation:3, height:15, width:15, alignSelf:'flex-end', margin:20}}>
                <FontAwesomeIcon icon={faTrash} size={15} color={"red"}/> 
            </TouchableOpacity>
        <Image source={item}
        key={index}
        style={{
          width:260,
          height:300,
          borderWidth:2,
          borderColor:'#d35647',
          resizeMode:'contain',
          margin:8
        }}
      />
      </View>
    )
    }

    const displayImages = () => {
            return (
                <FlatList
                  horizontal={true} 
                  showsHorizontalScrollIndicator={false} 
                  data={context.appData?.images}
                  extraData={context.appData?.images.length}
                  renderItem={renderItem}
                />
              );
    };
    
    return <View style={{marginTop:100, marginBottom:20}}>{displayImages()}</View>;
}

`

I am able to confirm that the context is updated with the images, if I go back a screen and then come back to the flatlist it is populated with all the images it just doesn't update while user remains on the screen.

I had previously used local state and a global state method and neither of these worked either. I've tried rearranging the code in a multitude of ways.

ryans
  • 1
  • 1

0 Answers0