1

I am trying to make a resuable fuction with the react-native imagepicker library but when i import the function i get undefined from the component i imported it to. With a console.log i see its actually working. it is just not showing the image uploaded.

I tried returning the source and the actually function but it doesnt work

helperfunction.js

import ImagePicker from 'react-native-image-picker';


export const photoUpload =()=>{
    const options = {
        title: 'Select Avatar',
        camera: [{ name: 'fb', title: 'Take a picture' }],
        storageOptions: {
          skipBackup: true,
          path: 'images',
        },
      };


     const action = ImagePicker.showImagePicker(options, (response) => {
        console.log('Response = ', response);

        if (response.didCancel) {
          console.log('User cancelled image picker');
        } else if (response.error) {
          console.log('ImagePicker Error: ', response.error);
        } else if (response.camera) {
          console.log('User tapped custom button: ', response.camera);
        } else {
          const source = { uri: response.uri };
          console.log(source)
           return  source; 

        }
      })
      return action;



}

App.js

import {photoUpload} from '../../../utilities/helper/photoUpload'

handlePhotoUpload =  async () =>{

    const data = await photoUpload()

    console.log(data) (this comes back undefined)
    if (data){
      this.setState({
        photo: data

      });
    }

  }
endlessCode
  • 1,255
  • 4
  • 21
  • 36

1 Answers1

6

If you have a look at the signature of the showImagePicker function from the docs, you'll see it has no return value:

static showImagePicker(options?, callback)

The reason you are still seeing results from the console log is that when you invoke the showImagePicker function it is calling your callback function asynchronously. To fix this issue, you can employ a promise like this:

export const photoUpload = () => {
    const options = {
        title: 'Select Avatar',
        camera: [{name: 'fb', title: 'Take a picture'}],
        storageOptions: {
            skipBackup: true,
            path: 'images',
        },
    };
    return new Promise(((resolve, reject) => {
        ImagePicker.showImagePicker(options, (response) => {
            if (response.didCancel) {
                reject('User cancelled image picker');
            } else if (response.error) {
                reject('ImagePicker Error: ', response.error);
            } else if (response.camera) {
                reject('User tapped custom button: ', response.camera);
            } else {
                const source = {uri: response.uri};
                resolve(source);
            }
        })
    }))
}

You can leave your app.js the same as you are already waiting for the promise to resolve with 'await' meaning the data variable will result in the source result object from the promise

CampbellMG
  • 2,090
  • 1
  • 18
  • 27