react-native-scanner/Pages/InitScanner/index.js

96 lines
2.6 KiB
JavaScript

import {useState} from 'react';
import {Constants} from '../../utils';
import {Button, HelperText, TextInput} from 'react-native-paper';
import {View} from 'react-native';
import EncryptedStorage from 'react-native-encrypted-storage';
export default function InitScanner({setScannerSession}) {
const [host, setHost] = useState('http://192.168.178.93:8080/v1/scanner');
const [scannerName, setScannerName] = useState('');
const onAddScanner = () => {
if (
scannerName.length >= Constants.GLOBALS.MIN_SCANNER_NAME_LENGTH &&
scannerName.length <= Constants.GLOBALS.MAX_SCANNER_NAME_LENGTH
) {
fetch(host, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
scannerName: scannerName,
}),
})
.then(res => {
if (res.status === 200) {
return res.json();
}
return Promise.reject(res.status);
})
.then(async data => {
await EncryptedStorage.setItem('scanner_host', host);
await EncryptedStorage.setItem('scanner_id', data.Id);
setScannerSession(data.Session);
})
.catch(err => {
console.error(err);
});
} else {
console.log('scanner name invalid');
}
};
const hasScannerNameErrors = () => {
return (
scannerName.length < Constants.GLOBALS.MIN_SCANNER_NAME_LENGTH ||
scannerName.length > Constants.GLOBALS.MAX_SCANNER_NAME_LENGTH
);
};
return (
<View
style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#2c3e50',
}}>
<TextInput
style={{
width: '80%',
borderRadius: 5,
marginBottom: 10,
}}
label="Host"
value={host}
onChangeText={value => setHost(value)}
/>
<TextInput
style={{
width: '80%',
borderRadius: 5,
marginBottom: 10,
}}
maxLength={Constants.GLOBALS.MAX_SCANNER_NAME_LENGTH}
label="Scanner name"
value={scannerName}
onChangeText={value => setScannerName(value)}
/>
<HelperText type="error" visible={hasScannerNameErrors()}>
{'Scanner name is invalid! Min: ' +
Constants.GLOBALS.MIN_SCANNER_NAME_LENGTH +
', Max: ' +
Constants.GLOBALS.MAX_SCANNER_NAME_LENGTH}
</HelperText>
<Button
disabled={hasScannerNameErrors()}
mode="contained"
onPress={() => onAddScanner()}>
Add scanner
</Button>
</View>
);
}