Reputation: 551
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
Upvotes: 2
Views: 5979
Reputation: 1
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
Upvotes: 0
Reputation: 1419
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
Upvotes: 18
Reputation: 1
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;
}
Upvotes: 0
Reputation: 1
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
}
]
}
Upvotes: 0
Reputation: 21
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)
}
})
}
Upvotes: 0