Accessing camera in React Native - reactjs

TL;DR: Doesn't work with IOS10 simulator. IOS9, however, seems fine.
I've been trying to implement L Wansbrough's react-native-camera module which everyone seems to recommend. After 10 hours of failing to get it to work, I really really need some help.
I gave up trying to get it into my existing project, so for now I'm just trying to do this from scratch in a brand new area. This is what I'm doing:
react-native init cameraProject
Okay, new project made. Let's just make sure the versions are right:
react-native -v
I get react-native-cli: 1.0.0 react-native: 0.36.0 returned. Just to check the requirements fully:
java -version
Returns: java version "1.8.0_112"
Java(TM) SE Runtime Environment (build 1.8.0_112-b16)
Java HotSpot(TM) 64-Bit Server VM (build 25.112-b16, mixed mode)
So the requirements look solid. Now:
react-native run-ios
Success - the app runs in the simulator, everything works as it should. Now I try and follow the documentation to install the react-native-camera. First off, there's a new requirements section regarding iOS10 which my simulator is running. You need to add the privacy key regarding the camera to the Info.plist file. This seems to have been omitted from the source code's example Info file and the documentation doesn't have the code required. I've dug around and added the following to cameraProject/ios/cameraProject/Info.plist:
<key>NSPhotoLibraryUsageDescription</key>
<string>Going to use some photos</string>
That's added in alphabetical order in the list, around line 25. Refreshing simulator and it's all good. Next:
npm install react-native-camera#https://github.com/lwansbrough/react-native-camera.git --save
followed by:
react-native link react-native-camera
Perfect; I get the messages I expect:
rnpm-install info Linking react-native-camera android dependency
rnpm-install info Android module react-native-camera has been successfully linked
rnpm-install info Linking react-native-camera ios dependency
rnpm-install info iOS module react-native-camera has been successfully linked
Everything still works as it should. Onto the 'Usage' section. I'm going to copy and paste the code out from GitHub into a module called BadInstagramCloneApp.js I'm then going to import that into index.ios.js with a basic import BadInstagramCloneApp from './BadInstagramCloneApp'; and we'll stick it in the main body with <BadInstagramCloneApp />.
Refresh the simulator:
Error
Alright, so quit the simulator, close Terminal and re-run react-native run-ios as I believe that should rebuild. It still doesn't work, throws:
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of 'cameraProject'.
I've loaded Xcode and looked at the manual instructions to link files. My library folder has the RCTCamera.xcodeproj file already. It's also already got libRCTCamera.a in the cameraProject->Build Phases->Link Binary with Libraries section. The Header Search Paths have the correct items in there and they are both marked as 'recursive' as per the instructions. Then CMD+R to run the project. New simulator loads, looks like it's going to work then falls over with the same red screen. Quit Xcode, run react-native run-ios again from Terminal (says build succeeded) and it's still giving the same error as above.
I've tried every permutation of this I can think of. I've tried copying the code from inside the example files, I've tried the older version of the module and I've followed a couple of tutorials online which are supposed to launch the react-native-camera as well. Not a single thing I've tried has ended in anything except a red screen or the application crashing out.
Suggestions? All I want to do is allow the user to take a photo and then return that photo as a Base64 encoded object.
index.ios.js
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import BadInstagramCloneApp from './BadInstagramCloneApp';
export default class cameraProject extends Component {
render() {
return (
<View style={styles.container}>
<BadInstagramCloneApp />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
}
});
AppRegistry.registerComponent('cameraProject', () => cameraProject);
BadInstagramCloneApp.js
'use strict';
import React, { Component } from 'react';
import {
AppRegistry,
Dimensions,
StyleSheet,
Text,
TouchableHighlight,
View
} from 'react-native';
import Camera from 'react-native-camera';
class BadInstagramCloneApp extends Component {
render() {
return (
<View style={styles.container}>
<Camera
ref={(cam) => {
this.camera = cam;
}}
style={styles.preview}
aspect={Camera.constants.Aspect.fill}>
<Text style={styles.capture} onPress={this.takePicture.bind(this)}>[CAPTURE]</Text>
</Camera>
</View>
);
}
takePicture() {
this.camera.capture()
.then((data) => console.log(data))
.catch(err => console.error(err));
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center',
height: Dimensions.get('window').height,
width: Dimensions.get('window').width
},
capture: {
flex: 0,
backgroundColor: '#fff',
borderRadius: 5,
color: '#000',
padding: 10,
margin: 40
}
});
// AppRegistry.registerComponent('BadInstagramCloneApp', () => BadInstagramCloneApp);
// AppRegistry.registerComponent('cameraProject', () => BadInstagramCloneApp);
module.exports = (BadInstagramCloneApp);
The console.log then throws this:
ExceptionsManager.js:62Cannot read property 'Aspect' of undefinedhandleException # ExceptionsManager.js:62handleError # InitializeJavaScriptAppEngine.js:120reportFatalError # error-guard.js:30guardedLoadModule # require.js:60_require # require.js:49(anonymous function) # require-0.js:1executeApplicationScript # debuggerWorker.js:20onmessage # debuggerWorker.js:38
RCTLog.js:38Running application cameraProject ({
initialProps = {
};
rootTag = 1;
})
ExceptionsManager.js:62Module AppRegistry is not a registered callable module (calling runApplication)handleException # ExceptionsManager.js:62handleError # InitializeJavaScriptAppEngine.js:120reportFatalError # error-guard.js:30guard # MessageQueue.js:48callFunctionReturnFlushedQueue # MessageQueue.js:107onmessage # debuggerWorker.js:44
ExceptionsManager.js:82Unhandled JS Exception: Cannot read property 'Aspect' of undefinedreactConsoleError # ExceptionsManager.js:82logIfNoNativeHook # RCTLog.js:38__callFunction # MessageQueue.js:236(anonymous function) # MessageQueue.js:108guard # MessageQueue.js:46callFunctionReturnFlushedQueue # MessageQueue.js:107onmessage # debuggerWorker.js:44
ExceptionsManager.js:82Unhandled JS Exception: Module AppRegistry is not a registered callable module (calling runApplication)
If I quit everything, reload, rebuild using react-native run-ios then the project builds correctly but crashes out after the splash screen is displayed. Console doesn't log any errors, but if I choose 'Pause on all caught exceptions' from the dev tools then it shows a stop here:
**_nodeUtil.js**
/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
try {
return freeProcess && freeProcess.binding('util');
} catch (e) {}
}());
If I try and run in from within Xcode rather than Terminal then it builds correctly, the simulator launches, but inside Xcode it opens cameraProject->Libraries->RCTCamera.xcodeproj->RCTCameraManager.m and highlights line 988:
[self.session commitConfiguration]; <Thread 1: EXC_BAD_ACCESS (code=1, address=0x50)
Any ideas on this?

I am having the same issue with a project I'm working on. According to this gitHub issue, the problem is a combination of new iOS 10 camera permissions and possibly also a problem with the simulator camera support itself. I've found that if I open the xcodeproj file directly in XCode, the simulator opens fine. I still haven't found a permanent fix but running build from XCode instead of react-native run-ios bypasses the issue for me. I'll follow up if I find a better option.

If I quit everything, reload, rebuild using react-native run-ios, then
the project builds correctly but crashes out after the splash screen
is displayed. Console doesn't log any errors, but if I choose 'Pause
on all caught exceptions' from the dev tools then it shows a stop
here:
_nodeUtil.js
Used to access faster Node.js helpers.
var nodeUtil = (function() {
try {
return freeProcess && freeProcess.binding('util');
} catch (e) {}
}());
I just can tell you that this is not relevant for your question, it always happen. Look here:
React Native - debugging exception

Related

RN FastImage react-native-fast-image failing with error "Generatedappglidemodule impl is implemented incorrectly"

Trying to integrate React Native Fast Image library https://github.com/DylanVann/react-native-fast-image. Package installation and linking is fine which generated
package.json
"react-native-fast-image": "^8.3.3"
MainApplicaition.java
import com.dylanvann.fastimage.FastImageViewPackage;
build.gradle
implementation project(':react-native-fast-image')
settings.gradle
include ':react-native-fast-image'
project(':react-native-fast-image').projectDir = new File(rootProject.projectDir,
'../node_modules/react-native-fast-image/android')
Usage in .ts file
import FastImage from 'react-native-fast-image'
<FastImage
style={{ width: 200, height: 200 }}
source={{
uri: 'https://unsplash.it/400/400?image=1',
//headers: { Authorization: 'someAuthToken' },
priority: FastImage.priority.normal,
}}
resizeMode={FastImage.resizeMode.contain}
/>
But every time getting the following error on android (haven't checked on iOS till now), although I have tried deleting node_modules, clearing watchman cache, tried adding excludeAppGlideModule = true as root project variable, downgrading the library version till 8.3.3 and added prograurd rules.
We are not using Glide dependency by using Picasso dependency.
Thanks for the help.

Error in Jimp.loadFont (use load-bmfont module) with React

I am testing Jimp.js for image manipulation (using React with react-scripts, npm: 6.14.4, node: v12.16.3)
Everything is going well except writing text on a loaded image
import Jimp from 'jimp'
Jimp.read(image)
.then(image => {
console.log('image loaded', image)
Jimp.loadFont(Jimp.FONT_SANS_32_WHITE).then(font => {
console.log('font loaded', font)
image.print(font, 10, 10, 'Hello world that wraps!', 12)
// write image
})
})
This throws an error "error parsing font malformed file -- no element" in browser.js of load-bmfont module line 71 and dont execute the log 'font loaded'.
Googling not help i found only 2,3 items about this, associate with using custom fonts - but i use standard font from Jimp. (Using BMFont files instead of Jimp standard fonts doesnt help)
My first thought was the error ocured in a React App in the browser, so i write a Jest test to see if its work without browser context but it fail just like that.
Got any ideas?
Solved...
I'm using the React App within a Java Web Framework in a JSP File.
Jimp.loadFont(Jimp.FONT_SANS_32_WHITE)
search the font in a path that doesn`t exist for the webapp.
Moving the font files to a reachable path with context root
Jimp.loadFont(`${CONTEXT_ROOT}/foo/bar/font.font`) works.

Why install a new library and want to use it, it shows an error?

I installed galio-frame.npm install galio-framework Then I used it.
import : import { Card } from 'galio-framework'; and then
<Card
flex
borderless
style={styles.card}
title="Christopher Moon"
caption="139 minutes ago"
location="Los Angeles, CA"
avatar="http://i.pravatar.cc/100?id=skater"
imageStyle={styles.cardImageRadius}
imageBlockStyle={{ padding: theme.SIZES.BASE / 2 }}
image="https://images.unsplash.com/photo-1497802176320-541c8e8de98d?&w=1600&h=900&fit=crop&crop=entropy&q=300"
/>
And when I run it with npx react-native run-android. I encounter this error. Of course, I have the same problem with installing and using other libraries.
WARN Require cycle: node_modules\galio-framework\src\index.js -> node_modules\galio-framework\src\Toast.js -> node_modules\galio-framework\src\index.js
Require cycles are allowed, but can result in uninitialized values. Consider refactoring to remove the need for a cycle.
Hi Try importing this way,
import Card from 'galio-framework';

workerize-loader failed to work after compiling (react typescript)

I created a rust-wasm module and use workerize-loader to load it:
export const getQRCode = async (
arg: string,
width: number,
height: number
) => {
const { qrcode } = await import('uranus-qrcode');
return qrcode(arg, width, height);
};
and then I use the worker as such:
// #ts-ignore
// eslint-disable-next-line import/no-webpack-loader-syntax
import qrCodeWorker from 'workerize-loader!workers/qrCodeWorker';
...
const workerizeQRLoader = async () => {
try {
const instance = qrCodeWorker();
const qr = await instance.getQRCode(href, 150, 150);
setQRCode({
__html: qr
});
} catch (e) {
console.warn(e);
}
};
...
useEffect(() => {
workerizeQRLoader();
// qrLoader();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
...
The above works in dev mode, but after compiling it says:
TypeError: a.getQRCode is not a function
at 8.a2ac9b2e.chunk.js:1
at l (0.69608c56.chunk.js:2)
at Generator._invoke (0.69608c56.chunk.js:2)
at Generator.forEach.e.<computed> [as next] (0.69608c56.chunk.js:2)
at r (0.69608c56.chunk.js:2)
at s (0.69608c56.chunk.js:2)
at 0.69608c56.chunk.js:2
at new Promise (<anonymous>)
at 0.69608c56.chunk.js:2
at 8.a2ac9b2e.chunk.js:1
If I import the rust-wasm module directly into the main thread it works:
...
const qrLoader = async () => {
const { qrcode: render } = await import('uranus-qrcode');
const qr = await render(href, 150, 150);
setQRCode({
__html: qr
});
};
useEffect(() => {
// workerizeQRLoader();
qrLoader();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
...
Basically I try to get React (Webpack & TypeScript flavor) to load WebAssembly modules (aka wasm, created via Rust-Wasmbindgen) through web workers. I've tried workerize-loader + wasm-loader, and it works pretty well in the dev mode but once it is compiled, the prototype will not be added to the worker (suspecting it's a bug in workerize-loader because all workerized modules behave the same). I also tried to work with worker-loader + comlink, but the worker-loader doesn't seem to work with wasm-loader (would not be able to import wasm into the worker). The only way to get this to work is to load wasm into the main thread via wasm-loader and just give up the multi-threads setup which is basically a shame...so does anyone have successfully use a WebAssembly module loaded through a web worker in a React TypeScript project? What's your setup?
I also created a starter project: https://github.com/aeroxy/react-typescript-webassembly-starter.git
You can checkout the "workerize" branch and see how it works in dev mode but after compiling, it throws "not a function" error.
This is a bit much for a comment but I got some bad and good news. Executed the following commands using node v12.16.1 and yarn 1.22.4:
git clone https://github.com/aeroxy/react-typescript-webassembly-starter.git
cd react-typescript-webassembly-starter
yarn # some warnings that packages need to be updated to later version
yarn start # dev version works
yarn build
cd build
npx serve
When opening the build version in Google Chrome 81.0.4044.113 (Official Build) (64-bit) on my Fedora 31 I can see the qr code, no errors in console.
That means that there is no fault in the project (good news) but something maybe wrong in settings on your machine (bad news), the os you are using or some other machine specific difference.
You could try a to clone the project again and run the commands exactly like I did to see if that's working. Older npm could have some problems with cached packages but that's been fixed for a while now. A while ago you needed to change the repository for npm or use vpn because it was blocked, this could also be causing you trouble.
This is a duplicate of my original answer but got deleted for some odd reason by a moderator without leaving a reason.
Now the workerize method works!
I've originally tried workerize-loader + wasm-loader, and it works pretty well in the dev mode but once it is compiled, the prototype will not be added to the worker (suspecting it's a bug in workerize-loader because all workerized modules behave the same). This indeed turns out to be a bug in workerize-loader (see workerize-loader failed to work after compiling and Version 1.2.0 does not export function on worker instance in production mode). After upgrading to the workerize-loader 1.2.1, it works in both dev and prod code.
I have updated the Master repo: https://github.com/aeroxy/react-typescript-webassembly-starter.git

Getting Error: Element type is invalid: error while upgrading Next.js from version 7 to 9.3

Here's the error that I am getting when upgraded existing working application to NextJs:
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
at ReactDOMServerRenderer.render (<path to project directory>\node_modules\react-dom\cjs\react-dom-server.node.development.js:3743:17)
at ReactDOMServerRenderer.read (<path to project directory>\node_modules\react-dom\cjs\react-dom-server.node.development.js:3373:29)
at renderToString (<path to project directory>\node_modules\react-dom\cjs\react-dom-server.node.development.js:3988:27)
at render (<path to project directory>\node_modules\next\dist\next-server\server\render.js:82:16)
at Object.renderPage (<path to project directory>\node_modules\next\dist\next-server\server\render.js:382:16)
at Function.getInitialProps (<path to project directory>\.next\server\static\development\pages\_document.js:483:19)
Existing application has custom _document.js. However, even after removing that still getting above error. (Above error is after removing custome _document.js). Cannot share application code here. However, following is the code snippet from .next\server\static\development\pages\_document.js file around line 483. Line number 483 in above error is await ctx.renderPage( line in following code.
static async getInitialProps(ctx) {
const enhancers = false ? undefined : [];
const enhanceApp = App => {
for (const enhancer of enhancers) {
App = enhancer(App);
}
return props => _react.default.createElement(App, props);
};
const {
html,
head
} = await ctx.renderPage({
enhanceApp
});
const styles = [...(0, _server.default)(), ...( false ? undefined : [])];
return {
html,
head,
styles
};
}
What did I try so far:
Googled for error
Tried to change import statements and commenting out portions of custom _document.js
Tried copying custom _document.js file example from NextJs documentation site
Removed custom _document.js
Deleted node_modules directory and ran npm install again
Deleted .next directory and restarted application again
Has anyone come across similar error? Thank you for your help. Any hint or clue also appreciated.
After spending lot of time commenting out and figuring out where 'import' is not correctly defined, found out the newer version of next-seo package needed named import rather than default for NextSeo. I had to go through lot of files to narrow down the code in error.
Wish there was better stack trace, especially when error it was showing was from _document.js !

Resources