How an error message can be shown when barcodes are not recognized by RNcamera ( react-native-camera) - react-native-camera

I am new to React-native. I have a requirement for barcode scanning and I am using react-native-camera for this. I want to show error message to the user when the barcodes are not recognized for some reason.
This is code.
class Scan extends Component {
constructor(props) {
super(props);
this.barocode = this.barocode.bind(this);}
barocode(e)
{
if(typeof (e) == 'undefined') // tried this if barcodes are not recognized. This doesn't work.
{
alert("error");
}
else{
this.camera.pausePreview();
alert(e.data);
}
}
render() {
return (
<View style={styles.container}>
<RNCamera
ref={ref => {
this.camera = ref;
}}
style = {styles.preview}
type={RNCamera.Constants.Type.back}
flashMode={RNCamera.Constants.FlashMode.on}
onBarCodeRead={(e) => {
this.barocode(e)}}
/>
</View>
);
}
OnbarcodeRead will call the function this.barocode(e) once it recognizes the barcode. This code is working fine for almost all barcodes types listed in the documentation.
https://www.npmjs.com/package/react-native-camera.
OnbarcodeRead will be undefined if barcodes are not recognized (this won't call the function this.barocode(e)).I want to show an error message that time. Could anyone guide me the way it can be done.

Related

Listen to keyboard input in the whole Blazor page

I'm trying to implement a Blazor app that listens to keyboard input all the time (some kind of full screen game, let's say).
I can think of a key down event listener as a possible implementation for it, since there's not really an input field to auto-focus on.
Is there a better solution to just react to key-presses in any part of the screen?
In case that's the chosen one, how can I add an event listener from a client-side Blazor app? I've failed trying to do so by having a script like this:
EDIT: I modified a little bit the code below to actually make it work after fixing the original, key mistake that I was asking about.
scripts/event-listener.js
window.JsFunctions = {
addKeyboardListenerEvent: function (foo) {
let serializeEvent = function (e) {
if (e) {
return {
key: e.key,
code: e.keyCode.toString(),
location: e.location,
repeat: e.repeat,
ctrlKey: e.ctrlKey,
shiftKey: e.shiftKey,
altKey: e.altKey,
metaKey: e.metaKey,
type: e.type
};
}
};
// window.document.addEventListener('onkeydown', function (e) { // Original error
window.document.addEventListener('keydown', function (e) {
DotNet.invokeMethodAsync('Numble', 'JsKeyDown', serializeEvent(e))
});
}
};
index.html
<head>
<!-- -->
<script src="scripts/event-listener.js"></script>
</head>
Invoking it through:
protected async override Task OnAfterRenderAsync(bool firstRender)
{
await jsRuntime.InvokeVoidAsync("JsFunctions.addKeyboardListenerEvent");
}
and having the following method trying to receive the events:
using Microsoft.AspNetCore.Components.Web;
using Microsoft.JSInterop;
namespace Numble;
public static class InteropKeyPress
{
[JSInvokable]
public static Task JsKeyDown(KeyboardEventArgs e)
{
Console.WriteLine("***********************************************");
Console.WriteLine(e.Key);
Console.WriteLine("***********************************************");
return Task.CompletedTask;
}
}
I manage to get the script executed, but I'm not receiving any events.
The name of the event is keydown, not onkeydown.

How to keep or store data in forms input fields. after form submitted in react native

I am new to react native. I have created a form. Now all work fine. But when I submit form. and after I clear expo app from recent apps and start again. then I want to show previous form filled data. in each input.
and user will able to edit it. so in short I want store or keep all input data in input field. so please help. thanks. is it possible. if yes then please help
here is my code
constructor(props) {
super(props);
this.state={
Place:"",
};
validateInputs = (event) => {
if (!this.state.Place.trim())
{
this.setState({ PlaceError: 'Field Should Not Be An Empty' })
return;
}
handlePlace = (text,event) => {
this.setState({ PlaceError: '' })
this.setState({ Place: text })
}
render(){
return (
<TextInput maxLength={50} placeholder="Place" style={styles.inputStyle}
onChangeText={this.handlePlace} defaultValue={this.state.Place} />
<Text style={{color :'red'}}>{this.state.PlaceError}</Text>

React Native - How to validate Textinput correclty?

How to validate Textinput correclty? I want to validate my form correctly with custom form validation and after validation display errors in Text component, but how? Please, guys show me example!
install react-native-snackbar to show error messages.
import React, { Component } from 'react';
import { View, Text, TextInput } from 'react-native';
import Snackbar from 'react-native-snackbar';
export default class LoginPasswordScreen extends Component {
constructor(props) {
super(props);
this.state = {
password: ''
}
}
validate = () => {
//include your validation inside if condition
if (this.state.password == "") {
() => {
setTimeout(() => {
Snackbar.show({
title: 'Invalid Credintials',
backgroundColor: red,
})
}, 1000);
}
}
else {
Keyboard.dismiss();
// navigate to next screen
}
}
render() {
return (
<View>
<TextInput
returnKeyType="go"
secureTextEntry
autoCapitalize="none"
autoCorrect={false}
autoFocus={true}
onChangeText={(password) => this.setState({ password })}
/>
<TouchableOpacity>
<Text onPress={this.validate}>Next</Text>
</TouchableOpacity>
</View>
);
}
}
Every field, you have to do a comparison and show the error message and as I see there is no direct form validation even though there is form component available in react native.
In One of my react native project, I added a form and later on click of Submit, I had written one validate function to check all my inputs.
For this, I used one nice javascript library-
npm library- validator
And for showing error message, you can use, Toast, ALert or Snackbar
Would be nice if you provide some thoughts or code on how you would think it can be approached. But the way i did it was pretty simple, on my component state i got the following object:
this.state = {
loading: false,
username: {
text: '',
valid: false
},
password: {
text: '',
valid: false
},
isLoginValid: false
};
Then on the TextInput for username, i would first, bind its value to this.state.username.text, also, during onChangeText I just do a simple validation of the field, if the form is quite big, you may have a switch(fieldtype) where you have for each field, what treatment you want to apply a.k.a validation.
onChangeText={ (text) => { this.validateInput(text, 'username')}} (username would be the form input on the state object)
For instance, for username you want only to be length != 0 and length <= 8 characters, for email you may run a RegExp() with the email validation and also its length, for password a different logic, etc... after that i just simply save the state for that field input and if it's valid or not. Like this:
validateInput(text, fieldname) {
let stateObject = {
text: text,
valid: text.length !== 0
}
this.setState({ [fieldname]: stateObject }, () => {
this.checkValidation();
});
}
In checkValidation I check for all the input fields and if every one is valid, i set formValid to true.
This formValid would for example, allow the user to tap on the "Login" button otherwise it applies an opacity of 0.5 to it and disables it.
The rest you may guess, is just playing around with the valid variables of each field to what you want to display and what not.
In a Register form I also added an X or a "Tick" icon if the input text field is ok or not. Let your imagination guide you.
Hope it helps.

How to detect when Mapbox/Leaflet enters or exits fullscreen mode

How can I detect when Mapbox or Leaflet enters or exits fullscreen mode?
I found this answer where someone said this:
Documentation says:
map.on('fullscreenchange', function () {
if (map.isFullscreen()) {
console.log('entered fullscreen');
} else {
console.log('exited fullscreen');
}
});
If doesnt work, use this instead:
map.on('enterFullscreen', function(){
});
map.on('exitFullscreen', function(){
});
I tried that, as well as a few variations of the event type parameter. No dice.
Also, the documentation doesn't mention an event for this.
Note that I am using Mapbox GL JS.
I know this is a late response but to anyone in the future this is how I approached it (for mapbox GL JS (without leaflet).
map.on("resize", () => {
if (document.fullscreenElement) // do something
});
You can give the map wrapper div a name and exclusively also check if the map is what triggered the fullscreen event
map.on("resize", () => {
if (document.fullscreenElement?.attributes.name.value === "mapWrapper") // do something
});
And if you are using React you can use a state to hold this information.
const [isFullScreen, setIsFullScreen] = useState();
...
map.on("resize", () => {
setIsFullScreen(
document.fullscreenElement?.attributes.name.value === "mapWrapper"
);
});
...
if (isFullScreen) //do something
This is actually really simple. You don't need anything from Leaflet or Mapbox. Just use an event listener on the document object.
let fullScreenChange;
if ('onfullscreenchange' in window.document) {
fullScreenChange = 'fullscreenchange';
} else if ('onmozfullscreenchange' in window.document) {
fullScreenChange = 'mozfullscreenchange';
} else if ('onwebkitfullscreenchange' in window.document) {
fullScreenChange = 'webkitfullscreenchange';
} else if ('onmsfullscreenchange' in window.document) {
fullScreenChange = 'MSFullscreenChange';
}
function onFullscreenChange() {
// Your stuff.
}
window.document.addEventListener(fullScreenChange, onFullscreenChange);

Ionic2: Unsubscribe Event to Avoid Duplicate Entries?

I've followed this tutorial which outlines adding monitoring beacons in an Ionic 2 application. I have it working great: when the view loads, it initializes and begins listening for beacons:
home.ts
ionViewDidLoad() {
this.platform.ready().then(() => {
this.beaconProvider.initialise().then((isInitialised) => {
if (isInitialised) {
this.listenToBeaconEvents();
}
});
});
}
This calls the listenToBeaconEvents function which populates a list in the view with all of the beacons:
home.ts
listenToBeaconEvents() {
this.events.subscribe(‘didRangeBeaconsInRegion’, (data) => {
// update the UI with the beacon list
this.zone.run(() => {
this.beacons = [];
let beaconList = data.beacons;
beaconList.forEach((beacon) => {
let beaconObject = new BeaconModel(beacon);
this.beacons.push(beaconObject);
});
});
});
}
I'm able to stop ranging using this.beaconProvider.stopRanging() that calls a function from the below function:
beacon-provider.ts
stopRanging() {
if (this.platform.is('cordova')) {
// stop ranging
this.ibeacon.stopRangingBeaconsInRegion(this.region)
.then(
() => {
console.log('Stopped Ranging');
},
error => {
console.error('Failed to stop monitoring: ', error);
}
);
}
}
The problem I'm having is this - in the original tutorial the beacon list is shown at the root, there's no other navigation. I've moved it to a different view, and if the user exits and re-enters the view, it re-initializes and loads everything, resulting in duplicate list entries.
I've tried creating a function within beacon-provider.ts to call before the view exits, but I can't figure out how to keep the subscriptions/events from duplicating.
I've tried this.delegate.didRangeBeaconsInRegion().unsubscribe(), and some other variations but they all result in runtime errors.
In your case you are using Ionic's Events API which has its own unsubscribe(topic, handler) function.
In your component, whenever you need to unsubscribe, you should call this with the same topic:
this.events.unsubscribe(‘didRangeBeaconsInRegion’);
This will remove all handlers you may have registered for the didRangeBeaconsInRegion.
If you want to unsubscribe one specific function, you will have to have registered a named handler which you can send with unsubscribe.
this.events.unsubscribe(‘didRangeBeaconsInRegion’,this.mySubscribedHandler);
And your home.ts would look like:
mySubscribedHandler:any = (data) => {
// update the UI with the beacon list
this.zone.run(() => {
this.beacons = [];
let beaconList = data.beacons;
beaconList.forEach((beacon) => {
let beaconObject = new BeaconModel(beacon);
this.beacons.push(beaconObject);
});
});
}
listenToBeaconEvents() {
this.events.subscribe(‘didRangeBeaconsInRegion’,this.mySubscribedHandler);
}