React Native Image Picker: Cannot read property 'showImagePicker' of undefined - javascript

I'm following the example exactly as shown in https://github.com/marcshilling/react-native-image-picker using react-native-image-picker, via terminal with react-native run-ios and coding via Atom editor.
I did npm install react-native-image-picker#latest --save and currently the dependency in package.json shows: "react-native-image-picker": "^0.22.8",
And I clicked a button to trigger the imagePicker but I am getting the error: Cannot read property 'showImagePicker' of undefined.
What am I doing wrong?
Here is the code
import ImagePicker from 'react-native-image-picker'
var Platform = require('react-native').Platform
var options = {
title: 'Select Avatar',
customButtons: [
{name: 'fb', title: 'Choose Photo from Facebook'},
],
storageOptions: {
skipBackup: true,
path: 'images'
}
}
export default class chooseImage extends Component {
constructor() {
super()
this.state = {
avatarSource: "",
}
}
_uploadImage() {
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.customButton) {
console.log('User tapped custom button: ', response.customButton);
}
else {
// You can display the image using either data...
const source = {uri: 'data:image/jpeg;base64,' + response.data, isStatic: true};
// or a reference to the platform specific asset location
if (Platform.OS === 'ios') {
const source = {uri: response.uri.replace('file://', ''), isStatic: true};
} else {
const source = {uri: response.uri, isStatic: true};
}
this.setState({
avatarSource: source
})
}
})
}
render() {
return (
<View style={styles.container}>
<TouchableHighlight
onPress={this._uploadImage}
underlayColor='transparent'
>
<Image
source={this.state.avatarSource} style={styles.uploadAvatar}
/>
</TouchableHighlight>
</View>
)
}
}
EDIT
When I console.log(ImagePicker)

use manual installation
set permission
/AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

cannot read property y of undefined means you have a statement x.y
such that x is undefined. in this case, x is ImagePicker.
My best guess is that your import statement causes the issue.
try this:
var ImagePicker = require('react-native-image-picker');
instead of
import ImagePicker from 'react-native-image-picker'
Which is also what the example suggests.
if you want to stick with the import statement,
try this:
import * as ImagePicker from 'react-native-image-picker'
Which imports the module as ImagePicker and puts it inside the scope.
For more info, see: MDN on import statement

I have been working for hours to solve this problem! Finally after adding correctly these lines in MainApplication.java it worked as a charm. Do not forget to rebuild the project.

it seems like IMagePicker is not defined.
Have you tried using
var ImagePicker = require('react-native-image-picker');
instead of the first line?

Hi there are few things that you can try: Run react-native link
Make sure you already completed this step
http://prntscr.com/hftr17
If not: your last chance is remove completely your code. Clone a new one.
I was successfully make it work by follow those.
Hope it can give you something.

Rebuild your app. Run the command react-native run-ios and react-native run-android.

Rebuilding your app will just mean you'll get the same error.
You need to go through Xcode for iOS and edit your settings.gradle manually for this to work:
https://github.com/react-community/react-native-image-picker
You don't need to do the steps for both Android and iOS, but the steps outlined for either platform are crucial
So unless you have already executed react-native link, you will need to go through each numbered steps and make sure your binaries are properly linked.

If you are using xcode and getting this error on simulator or real device make sure after installing and react link command you follow manual instructions. as described ie.
In the XCode's "Project navigator", right click on your project's Libraries folder ➜ Add Files to <...> .
Go to node_modules ➜ react-native-image-picker ➜ ios ➜ select RNImagePicker.xcodeproj
Add RNImagePicker.a to Build Phases -> Link Binary With Libraries
For iOS 10+, Add the NSPhotoLibraryUsageDescription, NSCameraUsageDescription, NSPhotoLibraryAddUsageDescription and NSMicrophoneUsageDescription (if allowing video) keys to your Info.plist with strings describing why your app needs these permissions.
Note. = RNImagePicker.a is now libRNImagePicker.a
and make sure you add this in your project build phase the lib's build phase itself.
Then you may compile and run it.

Note :
After installation you have to restart the project as react-native run-ios or
react-native run-android
May be u installed the picker but didn't restart the packager
: )

If you are using xcode and getting this error on simulator or real device make sure after installing and react link command you follow manual instructions. as described ie.
In the XCode's "Project navigator", right click on your project's Libraries folder ➜ Add Files to <...> .
Go to node_modules ➜ react-native-image-picker ➜ ios ➜ select RNImagePicker.xcodeproj
Add RNImagePicker.a to Build Phases -> Link Binary With Libraries
For iOS 10+, Add the NSPhotoLibraryUsageDescription, NSCameraUsageDescription, NSPhotoLibraryAddUsageDescription and NSMicrophoneUsageDescription (if allowing video) keys to your Info.plist with strings describing why your app needs these permissions.
Note. = RNImagePicker.a is now libRNImagePicker.a and make sure you add this in your project build phase the lib's build phase itself.
Then you may compile and run it.

As per your first comment you mentioned that you are not using Xcode you are using Atom and Terminal. In most of the cases only npm install will be enough but there are some platform specific cases that can be achieved either by linking it using react-native link or by following the manual installation steps provided in the document. if you are not using Xcode then its not possible for you to link this library completely for IOS platform. Make sure you use Xcode and follow the manual steps or else react-native link to solve your issue.

I had the same problem and in iOS it was due to the permission missing, even in the simulator. See the permissions here:
https://github.com/react-native-community/react-native-image-picker/blob/master/docs/Install.md
I just missed "NSPhotoLibraryAddUsageDescription" and it was enough to get the "Cannot read property 'showImagePicker' of undefined" error.

Related

React Native : Execution failed for task ':app:mergeAlphaDebugNativeLibs'

I am getting the following error and I am using React Native on Apple M1 chip and the react native version is 0.64.1
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:mergeAlphaDebugNativeLibs'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
> More than one file was found with OS independent path 'lib/armeabi-v7a/libfbjni.so'. If you are using jniLibs and CMake IMPORTED targets, see https://developer.android.com/studio/preview/features#automatic_packaging_of_prebuilt_dependencies_used_by_cmake
Please help me resolve this issues.
Tried add below code to the following file app/build.gradle, app was build successfully but it crashed.
android {
// yout existing code
packagingOptions {
pickFirst '**/libc++_shared.so'
pickFirst '**/libfbjni.so'
}
}
this work for me.
add to exclusiveContent 'android/build.gradle':
allprojects {
repositories {
exclusiveContent {
// We get React Native's Android binaries exclusively through npm,
// from a local Maven repo inside node_modules/react-native/.
// (The use of exclusiveContent prevents looking elsewhere like Maven Central
// and potentially getting a wrong version.)
filter {
includeGroup "com.facebook.react"
}
forRepository {
maven {
url "$rootDir/../node_modules/react-native/android"
}
}
}
//....
}
}
Remember run:
cd android && ./gradlew clean

How to debug Rollup build output with a massive encoding log?

I recently built a library with Rollup that has a few non-usual bits. That includes for instance, loading up a wasm module, workers with importScripts and a few occurences of eval() in the global scope.
Now I used the rollup-starter-app to create a demonstrator and client app for that library. The repo is https://github.com/frantic0/sema-engine-rollup
I managed to get everything working, after hitting a few walls and adding the following rollup plugins
import { wasm } from "#rollup/plugin-wasm";
import workerLoader from "rollup-plugin-web-worker-loader";
import dynamicImportVars from "#rollup/plugin-dynamic-import-vars";
import copy from "rollup-plugin-copy";
However, in the build output, I'm getting this massive log of what seems to be some encoding...
I'm not sure where this log is coming from and it is so massive that it clears out all the information of the build in the terminal...
What is the best way to tackle this issue and how to debug it effectively?
based on the suggestion #lukastaegert on the rollup issues, one solution is to redirect stderr into a file to read the log.
To do that you can add the following to your rollup command
"rollup -cw 2>err.log 1>out.log"
this allows to further inspect the build log but doesn't solve the error
[EDIT]
After a bit of peeking around Rollup's github issues and source, I found the warning categories and how to deactivate warnings.
Basically, we need to add a function onwarn to rollup.config.js. The first code section below shows the function. The second one show where we should add it on the rollup.config.js
const onwarn = (warning) => {
// Silence warning
if (
warning.code === 'CIRCULAR_DEPENDENCY' ||
warning.code === 'EVAL'
) {
return
}
console.warn(`(!) ${warning.message}`)
}
export default {= {
inlineDynamicImports: !dynamicImports,
preserveEntrySignatures: false,
onwarn,
input: `src/main.js`,
output: {

Migrating Nuxt to 2.7: refresh loop

I'm working on migrating a Nuxt.js project from Nuxt#1.4 to 2.7, and after updating the Webpack config as required, etc. I'm now running into the following error.
When I try to access any of the pages on the website, I hit the stock Nuxt loading screen showing bundling progress, which then immediately refreshes ad infinitum. The application never progresses past this screen, and the tab title never changes from Nuxt.js: Loading app....
There are no errors in the console, nor any compile time errors, but when I go to the devtools Network tab, I see a failed (HTTP 500) request to localhost:3000, with the following error as response payload:
NuxtServerError
render function or template not defined in component: NuxtLoading
I looked into NuxtLoading, and the only reference to it I can find is a file in the .nuxt folder called nuxt-loading.vue, which looks like a regular functioning component. It has a render() method, which is implemented as follows:
render(h) {
let el = h(false)
if (this.show) {
el = h('div', {
staticClass: 'nuxt-progress',
class: {
'nuxt-progress-notransition': this.skipTimerCount > 0,
'nuxt-progress-failed': !this.canSucceed
},
style: {
'width': this.percent + '%',
'left': this.left
}
})
}
return el
}
What I've tried:
Reinstall node_modules;
rm -rf .nuxt && yarn dev (EDIT: and yarn.lock);
Upgrading element-ui to latest version.
Thanks in advance for any help. If any more info is needed, please ask.
You have a wrong configuration for i18n loader. It should be like this:
config.module.rules.push({
resourceQuery: /blockType=i18n/,
type: 'javascript/auto',
loader: '#kazupon/vue-i18n-loader'
});
Or you can use nuxt-i18n module, that will setup this for you using vueI18nLoader option.

Importing iOS module from pod to nativescript plugin

Currently I have ventured into the world of development with NativeScript and a bit with Typescript, but now I have a problem that has been bothering me a lot.
I'm developing a plugin with the help of 'nativescript-plugin-seed' which makes use of a pod (AudioKit) for audio conversion. My question is the way I should import the 'AudioKit' module to the plugin in order to make use of its functions and then make use of them in an application
I include the code in Swift for the audio conversion that I tested in a Xcode project to verify its correct operation and the template where I suppose the module should be imported to generate the methods that will be communicated with my application.
Swift Code
import UIKit
import AudioKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let fileManager = FileManager.default
do {
let origin = Bundle.main.url(forResource: "IOS", withExtension: "mp4")
let documentDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create:false)
let destination = documentDirectory.appendingPathComponent("test.wav")
var options = AKConverter.Options();
options.format = "wav";
options.sampleRate = 48000;
options.bitDepth = 16;
let converter = AKConverter(inputURL: origin!, outputURL: destination, options: options)
converter.start(completionHandler: { error in
if(error != nil){
print("ERROR")
}else{
print("CORRECT")
}
})
}
catch {
print(error)
}
}
}
Plugin Code (my-plugin.ios.ts)
import { Common } from './audio-converter.common';
//I suppose the module should be declared here
export class AudioConverter extends Common {
// and used here
}
**EDITED
I already use the commands HERE but the typing files are never created. In the same way I read If the pod was written in Swift I have to configure the pod file and the build.xcconfig, however it doesn’t work anyway. I'll comment the steps I'm doing just to verify that I’m not doing something wrong.
Create the plugin with git clone
https://github.com/NativeScript/nativescript-plugin-seed and configuring the plugin's name.....
Add the podfile
pod 'AudioKit', '~> 4.0'
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['SWIFT_SWIFT3_OBJC_INFERENCE'] = 'On'
config.build_settings['SWIFT_VERSION'] = '4.0'
end
end
end
Add to build.xcconfig the flag ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES
Executing these commands for create the typing files in /src (-EDITED For create the typing files these commands must used in /demo)
TNS_DEBUG_METADATA_PATH="$(pwd)/metadata" tns build ios [--for-device] [--release]
TNS_TYPESCRIPT_DECLARATIONS_PATH="$(pwd)/typings" tns build ios [--for-device] [--release]
In this point I supose that I have to get the files in typing carpet but I don't get them
Once you have the POD setup, all the Objective C exposed apis from the library will be available for you to access. If you like to utilise TypeScript Intellisense for the library, then you will have to generate the typings first.
Here you will find the docs on generating typings. Once it's generated you will have to import them in your reference.d.ts.
If you are not already familiar with marshalling Objective C to JS / TS, then you might want to start here.

Devtron is unable to load the processes graph

I am learning to use Eletron and I found very useful this debugging tool: Devtron.
But it not works and I don't know if it is a bug or I am not using it correctly.
The installation guide from Devtron's website says:
# Install Devtron
$ npm install --save-dev devtron
// Run the following from the Console tab of your app's DevTools
require('devtron').install()
// You should now see a Devtron tab added to the DevTools
I did it correctly, and now I can see the Devtron tab on the Inspector panel:
But when I run my Quick Start by npm start application the graph does not show and I get following errors in the shell:
I looked for the faulty function in ./devtron/out/index.js
loadGraph () {
modules.getRenderModules().then((mainModule) => {
this.tableDescription.classList.add('hidden')
const suffix = this.getTabLabelSuffix(mainModule)
this.renderProcessTab.textContent = `Renderer Process ${suffix}`
this.renderRequireRows.innerHTML = ''
if (this.rootRenderView) this.rootRenderView.destroy()
this.rootRenderView = new ModuleView(mainModule, this.renderRequireRows)
this.rootRenderView.select()
}).catch((error) => {
console.error('Loading render modules failed')
console.error(error.stack || error)
})
But can't understand what wrong.
How to fix this problem?

Categories

Resources