I come here after two whole days without success. I want to increment my array with the pictures selected by the User, for return to my database a list of uri. But when the user choosed the first picture and re-open the android navigator for take a new picture, I saw the array doesn't increment. It takes the first value, and when I leave the selectImage() method it is back to empty.
Here is my main function :
EDIT :
const arrayImage = [];
const selectImage = () => {
const options = {
maxWidth: 2000,
maxHeight: 2000,
storageOptions: {
skipBackup: true,
path: 'images'
}
};
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 {
async(response);
}
})
function async(param) {
setTimeout(function() {
const source = { uri: param.assets[0].uri }
array ?
setImage(source)
: arrayImage.push(source)
console.log(arrayImage);
}, 2000);
}
console.log(arrayImage)
};
I tried with promises, changing my function in async, with a SetTimeOut but I guess the probleme is not with the Asynchronous. Someone for help ? Thanks a lot.
CodePudding user response:
Use useState for your array to keep state even if you leave the screen:
import { useState } from "react";
const yourComponent = () => {
const [array, setArray] = useState([]);
}
And in your function instead of array.push(source) you use it like that:
const newArray = [...array, source];
setArray(newArray);
And this should keep your result as I think the problem comes from the array and not the asynchronous function.