2

In my react-native app, I using react-native-image-picker to pick image from camera or gallery. But the resource.uri returned in undefined in both launchCamera and launchImageLibrary. What am I doing wrong?

Here is my github repo of a basic build of the react-native app. The image picker code is in addProductScreen.js

Kartikey
  • 4,516
  • 4
  • 15
  • 40
user2243481
  • 551
  • 5
  • 8

5 Answers5

17

I saw your problem and I have a solution for you. the response is a JSON object that contains an array called assets so you can access your image url by using this.

response.assets[0].uri

shammi
  • 1,301
  • 1
  • 10
  • 25
0

This helped me, and I can explain it so here is why!

response is a JSON object that contains an array called assets.

To access the first element of the array use .assets[0], then you can access the .uri, .fileName, etc..

{
  //response.uri is looking for the uri right here instead of inside assets[]
  "assets": [
    {
      "fileName": "yourImage.jpg",
      "fileSize": 123,
      "height": 123,
      "type": "image/jpeg",
      "uri": "yourImage.jpg",
      "width": 123
    }
  ]
}
Flair
  • 2,609
  • 1
  • 29
  • 41
0

Based on the answers above, this worked for:

const handleSelectImage = () => {
    const options = {
      noData: true,
      mediaType: 'photo' as const
    }
    launchImageLibrary(options, (response) => {
      if (response.assets) {
        const imageAssetsArray = response.assets[0].uri
        setImageState(imageAssetsArray)
      }
    })
}
Flair
  • 2,609
  • 1
  • 29
  • 41
Sheddy
  • 11
  • 2
0

I was scratching my head with this as well. I wrote a function to test what object was being returned from my photo selection:

    launchCamera(options, (response) => {
      if (response.assets && response.assets?.length !== 0) {
        setFilePath(response.assets[0].uri)
        console.log('ASSET OBJECT FOUND: ', response.assets[0].uri)
        return
      } else if (response.uri) {
        setFilePath(response.uri)
        console.log('NO ASSET OBJECT FOUND: ', response.uri)
        return
      } else if (response.didCancel) {
        return
      } else if (response.errorCode === 'camera_unavailable') {
        setNoCameraFound(true)
        return
      } else {
        setNeedsCameraAccess(true)
        return
      }
    })

When using my iPhone the Asset object was undefined, but on my Android it was there. If you're using TypeScript, it complains about response.uri unless you add that value to types.d.ts

    didCancel?: boolean;
    errorCode?: ErrorCode;
    errorMessage?: string;
    assets?: Asset[];
    uri?: string;
}
  • Did you manage to solve the issue with the undefined `Asset` object? I seem to have the same problem on my iPhone. – Dan Oct 23 '22 at 17:20
0

THIS SOLUTION BY @ shammi worked for me.... Be sure to log the result the console to the terminal before trying to use it just to make sure its in the expected format.

response.assets[0].uri