I'm working on a react native project.
I want to add multiple images in the useState hook without re-setting the state of the hook.
eg: I want to capture an image using the camera and update the hook with the file path (this is okay at the moment), then I want to capture another image through the camera and update the react hook with the previous value (need previous file path and new file path should be there).
problem is when I try to capture a new image and update the useState, the useState hook re-render the view, It'll delete the previous file path and stored a new file path.
I'm suffering from this issue, Please help me to find a solution. Thanks in advance.
const tempArray = [];
const [selectedFiles, setSelectedFiles] = useState([]);
// capturing the image --------------
const chooseFile = () => {
const options = {
title: 'Select an option',
storageOptions: {
skipBackup: true,
path: 'images',
},
};
ImagePicker.showImagePicker(options, (response) => {
// console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
onsole.log('ImagePicker Error: ', response.error);
} else {
// let source = response;
// You can also display the image using data:
let source = {
uri: 'data:image/jpeg;base64,' + response.data
};
createImageArray(source);
}
});
};
const createImageArray = (imageData: string) => {
// adding file path to temp array -> to get the selected images
tempArray.push(imageData);
setImagesToHooks();
console.log("tempArray.length : " + tempArray.length);
}
const setImagesToHooks = () => {
const imagesArray = Array.from(tempArray).map((result) => result);
console.log('images : ' + JSON.stringify(imagesArray));
// adding mapped array to state hook
setSelectedFiles(imagesArray);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…