Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

How to add multiple values to react hook without rendering the view

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);
                }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I couldn't find which image picker you were using. But I did understood the problem that the issue was regarding updating the array.

The problem is you are using a second variable to store previous file paths whereas you can use state itself to access previous file path.

Es6 introduced the new concept of spread operator. You can learn more about this concept through this blog.

Code Reference:

    const App = () => {
      const [selectedFiles, setSelectedFiles] = useState([]);
      const chooseFile = () => {
        const options = {
          title: 'Select an option',
          storageOptions: {
            skipBackup: true,
            path: 'images',
          },
        };
        ImagePicker.showImagePicker(options, (response) => {
          if (response.didCancel) {
            console.log('User cancelled image picker');
          } else if (response.error) {
            console.log('ImagePicker Error: ', response.error);
          } else {
            let source = {
              uri: 'data:image/jpeg;base64,' + response.data,
            };
            setImagesToHooks(source);
          }
        });
      };
      const setImagesToHooks = (newImage) => {
        // This will update the array. Refer the blog link for more information.
        let imagesArray = [...selectedFiles, newImage];
        setSelectedFiles(imagesArray);
      };

      // Return your code below
      return <React.Fragment/>
    };

Since the new update is dependent on previous state, so even after re-render the state is maintained and previous paths retain.

Note: I wasn't able to run the code since the package for image picker was not mentioned.

If you need you can use the below mentioned pickers for react native.

  1. react-native-image-picker
  2. react-native-document-picker

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...