Search code examples
react-nativeuse-state

how to use state for choosing multi image uri from react-native image-picker?


I am currently developing uploading photos through using react-native-picker

(launchImageLibrary)

When I bring a picture through useState,

const [images, setImages] = useState({});

const showImage = async () => {
  await launchImageLibrary(options, (response) => {
    if (response.didCancel) {
      console.log("User cancelled image picker");
    } else if (response.error) {
      console.log("ImagePicker Error: ", response.error);
    } else if (response.customButton) {
      console.log("User tapped custom button: ", response.customButton);
    } else {
      let results = [];
      response.assets.map((imageInfo) => results.push(imageInfo.uri));
      if (response.assets.length > 1) {
        // multi images. ***it doesn't work!!!***
        setImages([...results, ...images]);
      } else {
        //image only 1  **it works!**
        setImages(...results);
      }
    }
  });
};

in return

//Yes It works for only one
<Image source={{ uri: images }} style={{ width: 150, height: 150 }} />;

//It doesn't work for multi images
{
  images > 1 &&
    images.map((image, idx) => (
      <Image
        key={idx}
        style={{ width: 150, height: 150 }}
        source={{ uri: image }}
      />
    ));
}

JSON.value error occurs when I upload a lot of pictures.

I think this problem lies in dealing with objects, but I can't solve it.


Solution

  • If you wan't to support multiple images you should make a list like this

    [{uri:'...'},{uri:'...'}, etc...]

    So change your useState to be this

    const [images, setImages] = useState([]);
    

    And your showImage function to be this

    const showImage = async () => {
            await launchImageLibrary(options, response => {
                if (response.didCancel) {
                    console.log('User cancelled image picker');
                } else if (response.error) {
                    console.log('ImagePicker Error: ', response.error);
                } else if (response.customButton) {
                    console.log('User tapped custom button: ', response.customButton);
                } else {
                    let results = [];
                    response.assets.forEach(imageInfo => results.push(imageInfo.uri));
                    if (response.assets.length > 1) {
                        // multi images. ***it doesn't work!!!***
                        setImages([...results, ...images]); // a list
                    } else {
                        //image only 1  **it works!**
                        setImages(results); // a list 
                    }
                }
            });
        };
    

    Then do this below to show the images

    //It doesn't work for multi images
     {images.length !==0 &&  images.map((image, idx) => (
       <Image key={idx} style={{width: 150, height: 150}} source={{uri: image}} />
     ))}