Scan codes and error undefined is not an object - react-native

I would like to set up a scan for EAN13 codes, I am using the react-native-camera package but I ran into a **
TypeError: undefined is not an object (evaluating
'_reactNativeCamera.Camera.constants')
** and I will like your help to find out where is the error in my code.
If you can guide me, help me, that would be great, thank you very much.
import React, { Component } from 'react';
import {
Text,
View,
Alert,
TouchableOpacity,
Image
} from 'react-native';
import {Camera} from 'react-native-camera';
import styles from '../../../assets/styles'
export default class Ean13 extends Component {
constructor(props) {
super(props);
this.handleTourch = this.handleTourch.bind(this);
this.state = {
torchOn: false
}
}
onBarCodeRead = (e) => {
Alert.alert("Barcode value is" + e.data, "Barcode type is" + e.type);
}
render() {
return (
<View style={styles.container}>
<Camera
style={styles.preview}
torchMode={this.state.torchOn ? Camera.constants.TorchMode.on : Camera.constants.TorchMode.off}
onBarCodeRead={this.onBarCodeRead}
ref={cam => this.camera = cam}
aspect={Camera.constants.Aspect.fill}
>
<Text style={{
backgroundColor: 'white'
}}>BARCODE SCANNER</Text>
</Camera>
<View style={styles.bottomOverlay}>
<TouchableOpacity onPress={() => this.handleTourch(this.state.torchOn)}>
<Image style={styles.cameraIcon}
source={this.state.torchOn === true ? require('../../../assets/images/flash.png') : require('../../../assets/images/no-flash.png')} />
</TouchableOpacity>
</View>
</View>
)
}
handleTourch(value) {
if (value === true) {
this.setState({ torchOn: false });
} else {
this.setState({ torchOn: true });
}
}
}

You have used Camera
this should be RNCamera
import { RNCamera } from 'react-native-camera';
And read the constants from
RNCamera.constants.TorchMode.on
Check the docs
https://github.com/react-native-camera/react-native-camera/blob/master/docs/RNCamera.md

Related

how to print the contents of a viewshot without display it in react native?

I am using the library react-native-view-shot and I am trying to print the contents of a viewshot without display it.
If I don't hide the contents I can print without a problem, but I need to hide the contents.
If I hide the viewshot and try to print the contents like:
import { StatusBar } from 'expo-status-bar';
import React, {Component} from 'react';
import {Button, ScrollView, StyleSheet, Text, TextInput, View, alert, Alert} from 'react-native';
import {discoverPrinters, pingPrinter, printImage, registerBrotherListener} from 'react-native-brother-printers';
import ViewShot from "react-native-view-shot";
export default class App extends Component {
state = {
displayContents: false
};
render() {
const {displayContents} = this.state;
return (
<ScrollView style={{flex: 1}}>
{displayContents && (
<ViewShot ref={(e) => {
this.viewShot = e;
}} options={{format: "jpg", quality: 0.9}}>
{ <Text style={{fontSize: 24}}>
print something
</Text> }
<Text style={{fontSize: 24}}>
printer test
</Text>
</ViewShot>
)}
<View style={styles.container}>
<Text>
Test Connection
</Text>
<Button title="Print from Manual" onPress={() => {
this.viewShot.capture().then(uri => {
// this.viewShot.capture().then(() => {
// console.log("do something with ", uri);
printImage(
{
"modelName": "Brother PT-P950NW",
"ipAddress": " 192.168.118.1",
},uri, {autoCut: false}).then(() => {
console.log("Discover Manual Successful");
}).catch((err) => {
console.log(err);
console.log("Discover Manual failed")
});
});
}}/>
</View>
</ScrollView>
);
}
}
I get this error message:
TypeError: undefined is not an object (evaluating '_this3.viewShot.capture')
It's possible do that ?

How to prevent initial load from Algolia instant search in react native?

I have a users collection which I want to query as the user types, but when I switch to the Search Users Screen, all the users have populated on the screen even the search is empty.
How can I prevent this and only send the results to the client when he/she types in the search box??
I found some other links and resources but either they were too old, difficult to understand for me or using React instead of React Native.
I am a beginner developer and if you would be elaborate with the solution then that would be great.
This is my code:
SEARCH_USER.JS:
import React, {Component} from 'react';
import {
View,
Text,
TextInput,
Alert,
FlatList,
ActivityIndicator,
} from 'react-native';
import firestore from '#react-native-firebase/firestore';
import algoliasearch from 'algoliasearch';
import {
InstantSearch,
connectSearchBox,
connectInfiniteHits,
} from 'react-instantsearch-native';
import PropTypes from 'prop-types';
import InfiniteHits from '../components/Algolia Components/InfiniteHits';
class SearchAddBuddyScreen extends Component {
constructor(props) {
super(props);
this.state = {
loading: false,
value: null,
};
}
searchClient = algoliasearch(
'########',
'####################',
);
render() {
return (
<View>
<SecondaryHeader secondaryHeaderTitle="Add Buddies" />
<InstantSearch
searchClient={this.searchClient}
indexName="prod_USERSCOLLECTION"
onSearchStateChange={searchState =>
console.log('=====> ', searchState)
}>
<ConnectedSearchBox />
<InfiniteHits navigation={this.props.navigation} />
</InstantSearch>
</View>
);
}
}
class SearchBox extends Component {
render() {
console.log('Connected Search Box called');
return (
<View
style={[
textInput.generalTextInput,
{
marginBottom: 24,
alignSelf: 'center',
justifyContent: 'center',
},
]}>
<TextInput
placeholderTextColor="#333647"
style={[textInput.generalTextInput, {alignSelf: 'center'}]}
onChangeText={text => this.props.refine(text)}
value={this.props.currentRefinement}
placeholder={'Search'}
clearButtonMode={'always'}
spellCheck={false}
autoCorrect={false}
autoCapitalize={'none'}
/>
</View>
);
}
}
SearchBox.propTypes = {
refine: PropTypes.func.isRequired,
currentRefinement: PropTypes.string,
};
const ConnectedSearchBox = connectSearchBox(SearchBox);
export default SearchUserScreen;
InfiniteHits.js:
import React, {Component} from 'react';
import {StyleSheet, Text, View, FlatList} from 'react-native';
import {connectInfiniteHits} from 'react-instantsearch-native';
import AddFriendComponent from '../AddFriend';
class InfiniteHits extends Component {
constructor(props) {
super(props);
this.navigation = this.props.navigation;
}
_renderItem = ({item}) => {
return (
<AddFriendComponent
username={item.username}
fullName={item.fullName}
onPressUserProfile={() =>
this.props.navigation.navigate('UserProfile', {profileId: item.uid})
}
/>
);
};
render() {
return (
<FlatList
data={this.props.hits}
keyExtractor={item => item.objectID}
// ItemSeparatorComponent={() => <View style={styles.separator} />}
onEndReached={() => this.props.hasMore && this.props.refine()}
renderItem={this._renderItem}
/>
);
}
}
export default connectInfiniteHits(InfiniteHits);
After reading through more material I found this https://www.algolia.com/doc/guides/building-search-ui/going-further/conditional-requests/react/
And made the following changes to my code and it succeeded.
conditionalQuery = {
search(requests) {
if (
requests.every(({params}) => !params.query) ||
requests.every(({params}) => params.query === ' ') ||
requests.every(({params}) => params.query === ' ') ||
requests.every(({params}) => params.query === ' ')
) {
// Here we have to do something else
console.log('Empty Query');
return Promise.resolve({
results: requests.map(() => ({
hits: [],
nbHits: 0,
nbPages: 0,
processingTimeMS: 0,
})),
});
}
const searchClient = algoliasearch(
'########',
'###################',
);
return searchClient.search(requests);
},
};
render() {
return (
<View>
<SecondaryHeader secondaryHeaderTitle="Add Buddies" />
<InstantSearch
searchClient={this.conditionalQuery}
indexName="prod_USERSCOLLECTION"
onSearchStateChange={searchState =>
console.log('=====> ', searchState)
}>
<ConnectedSearchBox />
<InfiniteHits navigation={this.props.navigation} />
</InstantSearch>
</View>
);
}
This solution can still be improved for the spaces typed, but I don't know how to do that.

React-Native: Setting focus to custom component built off an array

I am trying to create a list of custom inputs based on an array, and when pressing the the enter key, I'd like the focus to automatically move to the next custom input. I can get this to work with a regular <TextInput> react component using the ref and onSubmitEditing but I cannot get this to function properly using my custom component that wraps a <TextInput>
Here is my code, it consists of two files: App.js and TextInput2.js (I know that currently the last line will error because of the reference counter but if I can get it to work I'll address the last issue)
Working Snack
-- App.js --
import React from 'react';
import { StyleSheet, View, TextInput } from 'react-native';
import TextInput2 from './TextInput2'
export default class App extends React.Component {
constructor(){
super();
this.myRef = [];
this.state = {}
}
focusField = (key) => {
this.myRef[key].focus()
}
render() {
let textFields = ["one", "two", "three", "four", "five"];
return (
<View style={styles.container}>
{
textFields.map((x, i) => {
this.myRef[i] = React.createRef();
let k = i + 1
return(
<TextInput2
name={x}
key={i}
placeholder={x + " This Doesnt Work"}
ref={ref => this.myRef[i] = ref}
nextRef={this.myRef[k]}
//onSubmitEditing={() => this.focusField(k)}
//onSubmitEditing={() => this.myRef[k].focus()}
blurOnSubmit={false}
/>
)
})
}
{
textFields.map((x, i) => {
this.myRef[i] = React.createRef();
return(
<TextInput
name={x}
key={i}
placeholder="This works!"
ref={ref => this.myRef[i] = ref}
onSubmitEditing={() => this.focusField(i+1)}
blurOnSubmit={false}
/>
)
})
}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
});
--TextInput2.js --
import React from 'react';
import { View, TextInput } from 'react-native';
export default class TextInput2 extends React.Component {
state={}
handleFocus = () => {}
handleBlur = () => {}
focus() {
this.props.nextRef.focus()
}
render() {
return (
<View >
<TextInput
{...this.props}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
onSubmitEditing={() => this.focus()}
/>
</View>
)
}
}
I've read this post and this but cannot seem to determine how to setup the function to set focus on the next field.
I have edited the Snack. Please try this
I think you're making it complicated. Try to change like this,
this.myRef[index] = React.createRef()
CustomTextComponent component
<CustomTextComponent
name={Something}
key={index}
forwardRef={this.myRef[index]}
onSubmitEditing={() => this.myRef[index + 1].current.focus()}
/>
As you're using createRef() you have to call it's ref using the "current" object.
CustomComponent.js
import React from 'react';
import { View, TextInput } from 'react-native';
export default class CustomComponent extends React.Component {
render() {
return (
<View >
<TextInput
{...this.props}
returnKeyType={"next"}
ref={this.props.forwardRef}
onSubmitEditing={this.props.onSubmitEditing}
/>
</View>
)
}
}

TypeError: undefined is not an object (evaluating '_this.state = { showAddress: false}')

I am just trying the set the state variable to false, but I keep getting an error message
TypeError: undefined is not an object (evaluating '_this.state = {
showAddress: false
}')
I have hunted the internet for an answer on this and this error seem to be quite common in a general term. I have tried binding it to the function but nothing I do seem to change that error message.
import React, { Component } from 'react';
import { StyleSheet, Text, View, TextInput, TouchableHighlight, Alert} from 'react-native';
export default class PickupLocation extends React.Component {
constructor() {
this.state = {
showAddress: false
};
/* this.submitAddress = this.submitAddress.bind(this);
this.renderSubmitAddress = this.renderSubmitAddress.bind(this);*/
}
submitAddress = () => {
this.setState({
showAddress: !this.state.showAddress
})
}
renderSubmitAddress = () => {
if(this.state.showAddress){
return (
<View><Text>Jason Was Here</Text></View>
)
} else {
return null;
};
}
render() {
return (
<View style={styles.textArea} >
<View>
<TextInput
style={{height: 40, borderColor: 'gray', backgroundColor: 'white', borderWidth: 1}}
onChangeText={(text) => this.setState({text})}
placeholder="What is your pickup point?"
placeholderTextColor='grey'
onSubmitEditing={this.submitAddress()}
/>
{this.renderSubmitAddress()}
<View style={styles.Button} >
<TouchableHighlight buttonStyle={styles.Button} title="Press Me"
onPress={() => {Alert.alert("jason is testing");}} >
<Text style={styles.submitText}>Submit Pickup Location</Text>
</TouchableHighlight>
</View>
</View>
</View>
)
}
}
I will most likly get a duplicate on this question but I ave tried everything I could find here and none of the answers seem to change anything.
Thanking you in advance for any help.
You need to call super() in your constructor.
constructor() {
super();
this.state = {
showAddress: false
};
}
Additionally, there are a couple of other items that should be fixed.
When you access the current state in a setState call, you should use the version that takes a function as an argument, like so:
submitAddress = () => {
this.setState((prevState) => ({
showAddress: !prevState.showAddress
}))
}
Also, the handler you're passing to onSubmitEditing should be modified:
onSubmitEditing={this.submitAddress.bind(this)}

undefined is not an object(evaluating '_this.refs.toast.show')

My aim is to listen the event for Android homeback button, and then give a toast when continuous click. Here the third component "react-native-easy-toast" is used, fully code snippets shown as below:
import React, { Component } from 'react';
import {View, WebView, Platform, BackHandler, StyleSheet} from 'react-native';
import Toast, {DURATION} from 'react-native-easy-toast';
export default class HomeScreen extends Component {
constructor (props) {
super(props);
}
onNavigationStateChange = (event) => {
this.setState({
navCanGoBack : event.canGoBack,
});
};
componentDidMount() {
if (Platform.OS === 'android') {
BackHandler.addEventListener('hardwareBackPress', this.onHomeBackPress);
}
}
onHomeBackPress = () => {
if (this.state.navCanGoBack) {
this.refs['webview'].goBack();
return true;
} else {
//exit app if exceed 2 seconds
if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
return false;
}
this.lastBackPressed = Date.now();
this.refs.toast.show('weill exit app press again');
return true;
}
};
render() {
return (
<View style={{flex:1}}>
<WebView
source={{ uri: 'http://www.test.com/' }}
style={{ width: '100%', height: '100%' }}
ref="webview"
onNavigationStateChange={this.onNavigationStateChange}
/>
<Toast ref="toast" />
</View>
);
}
}
Finally, run the app and error given:
undefined is not an object(evaluating '_this.refs.toast.show')
I am newer to React Native.
Please try
//inside constructor
this.toastRef = React.createRef();
...
<Toast ref={this.toastRef} />
and replace
this.refs.toast.show('weill exit app press again');
to
this.toastRef.current.show('weill exit app press again');