native-base#Item JavaScript Examples
The following examples show how to use
native-base#Item.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Form.js From react-native-expo-starter-kit with MIT License | 5 votes |
ArticlesForm = ({
error, loading, success, onFormSubmit, defaultValues,
}) => {
const {
register, handleSubmit, errors, setValue,
} = useForm({ defaultValues });
useEffect(() => {
register({ name: 'email' }, { required: errorMessages.missingEmail });
}, [register]);
return (
<Container>
<Content padder>
<Header
title="Example form"
content="When you submit the form, it'll simply save to your redux store"
/>
{error && <Messages message={error} />}
{loading && <Messages type="info" message="Loading..." />}
{success && <Messages type="success" message={success} />}
<Form>
<Item stackedLabel>
<Label>Email*</Label>
<Input
type="text"
autoCapitalize="none"
placeholder="[email protected]"
keyboardType="email-address"
defaultValue={defaultValues.email || ''}
onChangeText={(value) => setValue('email', value)}
/>
</Item>
{errors.email && <Text>{errors.email.message}</Text>}
<Spacer size={20} />
<Button block onPress={handleSubmit(onFormSubmit)} disabled={loading}>
<Text>{loading ? 'Loading' : 'Submit'}</Text>
</Button>
</Form>
</Content>
</Container>
);
}
Example #2
Source File: ForgotPassword.js From expo-ticket-app with MIT License | 5 votes |
render () {
const { loading, error, success } = this.props;
const { email } = this.state;
return (
<KeyboardAvoidingView
style={{ backgroundColor: commonColor.backgroundColor, flex: 1 }}
behavior={(Platform.OS === 'ios') ? 'padding' : null}
enabled
keyboardVerticalOffset={Platform.select({ ios: 80, android: 500 })}>
<ScrollView contentContainerStyle={{ height: 400 }}>
<StatusBar style="light"/>
<Container style={{ backgroundColor: commonColor.backgroundColor }}>
<Content padder>
<Card style={{ backgroundColor: commonColor.backgroundColor }}>
{error && <View style={{ margin: 10 }}><Messages message={error}/></View>}
{success &&
<View style={{ margin: 10 }}><Messages type="success" message={success}/></View>}
<Form>
<Item floatingLabel style={{ margin: 15 }}>
<Label style={{ color: '#fff', fontFamily: 'Montserrat' }}>
{i18n.t('login.forgotLabel')}
</Label>
<Input
style={{ color: '#fff', fontFamily: 'Montserrat' }}
autoCapitalize="none"
value={email}
keyboardType="email-address"
disabled={loading}
onChangeText={v => this.handleChange('email', v)}
/>
</Item>
<Spacer size={20}/>
<ButtonH2t text={'login.forgotBtn'} loading={loading} onPress={this.handleSubmit}/>
</Form>
</Card>
</Content>
</Container>
</ScrollView>
</KeyboardAvoidingView>
);
}
Example #3
Source File: ChatListScreen.js From SocialApp-React-Native with MIT License | 4 votes |
ChatListScreen = (props) => {
const loggedUser = useSelector(state => state.auth.user);
const chatList = useSelector(state => state.chat.chatList);
const allChats = useSelector(state => state.chat.allChats);
let allUsers = useSelector(state => state.users.allUsers);
// remove logged user from the list
allUsers = allUsers.filter(item => item._id !== loggedUser._id);
const [isLoading, setIsLoading] = useState(false);
const [isRefreshing, setIsRefreshing] = useState(false);
const [searchText, setSearchText] = useState('');
const [data, setData] = useState(chatList);
const dispatch = useDispatch();
const loadChatList = useCallback(async () => {
setIsRefreshing(true);
try {
const result = await dispatch(chatActions.fetchChatList());
await dispatch(chatActions.fetchChats());
setData(result);
} catch (err) {
console.log(err)
}
setIsRefreshing(false);
}, [dispatch, setIsLoading])
const loadChats = useCallback(async () => {
try {
await dispatch(chatActions.fetchChats());
} catch (err) {
console.log(err)
}
}, [dispatch, setIsLoading])
// useEffect(() => {
// const unsubscribe = props.navigation.addListener('focus', e => {
// setSearchText('');
// loadChatList();
// });
// return () => {
// unsubscribe();
// };
// }, [])
useEffect(() => {
setIsLoading(true);
loadChats()
.then(() => {
setIsLoading(false);
});
setIsLoading(false)
}, [dispatch, loadChats])
const handleSearchTextChange = (text) => {
setSearchText(text);
if(text !== ''){
let filteredData = []
let currData = allUsers;
filteredData = currData.filter(item => {
const lc = item.name.toLowerCase();
text = text.toLowerCase();
return lc.includes(text);
});
setData(filteredData);
} else {
setData(chatList);
}
}
if (isLoading) {
return (
<View style={styles.centered} >
<ActivityIndicator size='large' color={Colors.primary} />
</View>
);
}
return (
<Container>
<Header style={{ backgroundColor: Colors.brightBlue }} searchBar rounded>
<Item>
<Icon name="ios-search" />
<Input
value={searchText}
onChangeText={(text) => handleSearchTextChange(text)}
placeholder="Search"
/>
<Icon name="ios-people" />
</Item>
</Header>
{ data.length === 0 && (
<View style={styles.centered}>
<Text>No chats !</Text>
<Text>Either your search does not match any user's name</Text>
<Text>or you have no chats.</Text>
<Text>Please refresh if you have new chats.</Text>
</View>
) }
<FlatList
data={data}
refreshing={isRefreshing}
onRefresh={loadChatList}
keyExtractor={(item) => item._id}
renderItem={(user) => (
<ChatListItem user={user.item} />
)}
/>
</Container>
);
}
Example #4
Source File: ChatTextInput.js From WhatsApp-Clone with MIT License | 4 votes |
ChatTextInput = ({params, onSendMessage, isStatus, onResetClick}) => {
const [message, setMessage] = useState('');
const [keyboardPadding, setKeyboardPadding] = useState(5);
useEffect(() => {
let listener1 = Keyboard.addListener('keyboardWillShow', onShowKeyboard);
let listener2 = Keyboard.addListener('keyboardWillHide', onHideKeyboard);
return () => {
listener1.remove();
listener2.remove();
};
}, []);
function onShowKeyboard(e) {
// alert('Keyboard Shown');
console.log(e);
setKeyboardPadding(
(e.endCoordinates.height - e.startCoordinates.height) / 2,
);
}
function onHideKeyboard(e) {
// alert('Keyboard Hidden');
setKeyboardPadding(0);
}
const getChatRoomInput = () => {
return (
<View style={{flexDirection: 'row'}}>
<Item rounded style={{backgroundColor: WHITE, flex: 1}}>
<Icon
name="smiley"
type="Octicons"
style={[styles.menuIcons, {marginLeft: 5}]}
/>
<Input
multiline
style={styles.userMessage}
placeholder="Type a message ..."
placeholderTextColor={LIGHT_GRAY}
value={message}
onChangeText={text => {
setMessage(text);
}}
/>
<Icon name="attachment" type="Entypo" style={styles.menuIcons} />
<Icon
name="camera"
type="MaterialCommunityIcons"
style={[styles.menuIcons, {marginRight: 5}]}
/>
</Item>
<Button
icon
rounded
large
style={styles.sendIconView}
onPress={() => {
onSendMessage(message);
setMessage('');
}}>
<Icon
name={message === '' ? 'microphone' : 'send'}
type="MaterialCommunityIcons"
style={styles.sendIcon}
/>
</Button>
</View>
);
};
const getStatusInput = () => {
return (
<View
style={{
flexDirection: 'row',
paddingBottom: '2%',
justifyContent: 'center',
}}>
<Button
rounded
style={styles.sendStatusIconView}
onPress={() => {
onResetClick();
setMessage('');
}}>
<Icon
name="camera"
type="MaterialCommunityIcons"
style={[styles.sendIcon]}
/>
</Button>
<Input
multiline
style={styles.userStatusMessage}
placeholder="Type a message ..."
placeholderTextColor={LIGHT_GRAY}
value={message}
onChangeText={text => {
setMessage(text);
}}
/>
<Button
icon
rounded
large
style={styles.sendStatusIconView}
onPress={() => {
onSendMessage(message);
setMessage('');
}}>
<Icon
name={'send'}
type="MaterialCommunityIcons"
style={styles.sendIcon}
/>
</Button>
</View>
);
};
return (
<KeyboardAvoidingView style={{paddingBottom: keyboardPadding}}>
<View style={styles.parentView}>
{isStatus ? getStatusInput() : getChatRoomInput()}
</View>
</KeyboardAvoidingView>
);
}
Example #5
Source File: _TextInput.js From WhatsApp-Clone with MIT License | 4 votes |
render() {
const {isFocused} = this.state;
const {defaultItem, defaultLabel, defaultInput} = inputDefaultStyle;
const {
ref,
isMandatory,
placeholder,
value,
editable = true,
leftIcon,
rightIcon,
labelStyle,
containerStyle,
inputStyle,
leftIconType,
rightIconType,
rightIconColor,
secureTextEntry,
keyboardType,
returnKeyType,
getRef,
refKey,
maxLength,
inlineImageLeft,
inlineImagePadding,
numberOfLines,
returnKeyLabel,
multiline,
selectionColor,
defaultValue,
floatingLabel,
textAlign,
} = this.props;
return (
<Item
floatingLabel={floatingLabel}
style={[
defaultItem,
containerStyle,
{
borderBottomWidth: isFocused ? 2 : 2,
borderBottomColor: isFocused ? GREEN : GREEN,
},
]}>
{/* <Icon style={{color: INPUT_ICON}} name={leftIcon} type={leftIconType} /> */}
{/* <Label style={[defaultLabel, labelStyle]}> {placeholder}</Label> */}
<Input
ref={ref}
selectionColor={selectionColor}
maxLength={maxLength}
editable={editable}
value={value}
secureTextEntry={secureTextEntry}
style={[
defaultInput,
inputStyle,
{color: !editable ? DISABLED_GRAY : INPUT_TEXT},
]}
autoCapitalize="words"
keyboardType={keyboardType}
returnKeyType={returnKeyType}
onChangeText={this.onChangeText}
onSubmitEditing={this.onSubmitEditing}
getRef={ref => getRef && getRef({refKey, ref})} //need to use getRef in case of floatingLabel
inlineImageLeft={inlineImageLeft}
inlineImagePadding={inlineImagePadding}
numberOfLines={numberOfLines}
returnKeyLabel={returnKeyLabel}
onFocus={this.handleInputFocus}
onBlur={this.handleInputBlur}
multiline={multiline}
onEndEditing={this.onEndEditing}
autoFocus={this.props.autoFocus}
defaultValue={defaultValue}
textAlign={textAlign}
/>
{rightIcon && (
<Icon
onPress={this.onRightIconPressed}
style={{color: rightIconColor, fontSize: 16}}
name={rightIcon}
type={rightIconType}
/>
)}
<Icon
// onPress={this.onRightIconPressed}
style={{color: isMandatory ? RED : rightIconColor, fontSize: 8}}
name={isMandatory ? 'asterisk' : ''}
type={isMandatory ? 'Foundation' : ''}
/>
</Item>
);
}
Example #6
Source File: ReportForm.js From pandoa with GNU General Public License v3.0 | 4 votes |
function ReportForm({ reportCaseTrigger, positions }) {
const { control, handleSubmit, errors } = useForm();
const onSubmit = data => {
Alert.alert("Data submitted");
reportCaseTrigger(positions);
// Alert.alert("Form Data", JSON.stringify(data), positions.length);
};
return (
<View>
<Form>
<Text style={styles.hintText}>
On this page you can report if you have got an infection. Please enter
your details below
</Text>
<View style={styles.inputWrapper}>
<Item>
<Text>Picker</Text>
<Controller
as={e => {
console.log(e);
return (
<Picker
note
mode="dropdown"
style={{ width: 120 }}
selectedValue={"key3"}
onValueChange={() => {}}
>
<Picker.Item label="Wallet" value="key0" />
<Picker.Item label="ATM Card" value="key1" />
<Picker.Item label="Debit Card" value="key2" />
<Picker.Item label="Credit Card" value="key3" />
<Picker.Item label="Net Banking" value="key4" />
</Picker>
);
}}
control={control}
name="firstName"
onChange={args => args[0].nativeEvent.text}
onChange={e => {
return "key1";
// Place your logic here
return selected;
}}
rules={{ required: true }}
defaultValue=""
placeholder="Username"
/>
</Item>
{errors.firstName && <Text>This is required.</Text>}
<Item>
<Controller
as={Input}
control={control}
name="lastName"
onChange={args => args[0].nativeEvent.text}
defaultValue=""
placeholder="Password"
/>
</Item>
</View>
<Text style={styles.hintText}>
Enter a contact phone number. This can be yours or a doctors phone
number.
</Text>
<View style={styles.inputWrapper}>
<Item>
<Label>Contact phone number</Label>
<Controller
as={Input}
control={control}
name="contact_phone"
onChange={args => args[0].nativeEvent.text}
defaultValue=""
/>
</Item>
</View>
<Text style={styles.hintText}>Enter information for you contact.</Text>
<View style={styles.inputWrapper}>
<Item style={styles.input}>
<Label>Contact information</Label>
<Controller
as={Input}
control={control}
name="contact_information"
onChange={args => args[0].nativeEvent.text}
defaultValue=""
placeholder="Contact information"
/>
</Item>
</View>
</Form>
{/*
<Form>
<Item>
<Input placeholder="Username" />
</Item>
<Item last>
<Input placeholder="Password" />
</Item>
<Button primary onPress={reportButton}>
<Text>Submit data</Text>
</Button>
</Form>*/}
<View style={styles.submitWrapper}>
<Button primary onPress={handleSubmit(onSubmit)}>
<Text>Submit</Text>
</Button>
</View>
</View>
);
}
Example #7
Source File: UpdateProfile.js From expo-ticket-app with MIT License | 4 votes |
render () {
const { loading, error, success } = this.props;
const {
firstName, lastName, email, changeEmail, changePassword,
} = this.state;
return (
<Container style={{ backgroundColor: commonColor.backgroundColor }}>
<StatusBar style="light"/>
<Content padder>
<Header
title={i18n.t('profile.myAccount')}
content={i18n.t('profile.updateAccount')}
/>
{error && <Messages message={error}/>}
{success && <Messages message={success} type="success"/>}
<Form>
<Item stackedLabel>
<Label style={{ fontFamily: 'Montserrat', color: '#fff' }}>
{i18n.t('login.fields.firstName')}
</Label>
<Input
value={firstName}
style={{ fontFamily: 'Montserrat', color: '#fff' }}
disabled={loading}
onChangeText={v => this.handleChange('firstName', v)}
/>
</Item>
<Item stackedLabel>
<Label style={{ fontFamily: 'Montserrat', color: '#fff' }}>
{i18n.t('login.fields.lastName')}
</Label>
<Input
value={lastName}
style={{ fontFamily: 'Montserrat', color: '#fff' }}
disabled={loading}
onChangeText={v => this.handleChange('lastName', v)}
/>
</Item>
<ListItem icon onPress={() => this.handleChange('changeEmail', !changeEmail)}>
<Body>
<TextH2t>{i18n.t('login.fields.email')}</TextH2t>
</Body>
</ListItem>
{changeEmail && (
<Item stackedLabel>
<Label style={{ fontFamily: 'Montserrat', color: '#fff' }}>{i18n.t('login.fields.email')}</Label>
<Input
autoCapitalize="none"
value={email}
style={{ fontFamily: 'Montserrat', color: '#fff' }}
keyboardType="email-address"
disabled={loading}
onChangeText={v => this.handleChange('email', v)}
/>
</Item>
)}
<ListItem icon onPress={() => this.handleChange('changePassword', !changePassword)}>
<Body>
<TextH2t>{i18n.t('profile.updatePassword')}</TextH2t>
</Body>
</ListItem>
{changePassword && (
<View padder>
<Item stackedLabel>
<Label style={{ fontFamily: 'Montserrat', color: '#fff' }}>{i18n.t('login.fields.password')}</Label>
<Input
secureTextEntry
style={{ fontFamily: 'Montserrat', color: '#fff' }}
onChangeText={v => this.handleChange('password', v)}
disabled={loading}
/>
</Item>
<Item stackedLabel last>
<Label style={{ fontFamily: 'Montserrat', color: '#fff' }}>{i18n.t('login.fields.confirmPassword')}</Label>
<Input
secureTextEntry
style={{ fontFamily: 'Montserrat', color: '#fff' }}
onChangeText={v => this.handleChange('password2', v)}
disabled={loading}
/>
</Item>
</View>
)}
<Spacer size={20}/>
<ButtonH2t text={'login.update'} onPress={this.handleSubmit}/>
</Form>
</Content>
</Container>
);
}
Example #8
Source File: SignUp.js From expo-ticket-app with MIT License | 4 votes |
render () {
const { loading, error, success } = this.props;
return (
<KeyboardAvoidingView
style={{ backgroundColor: commonColor.backgroundColor, flex: 1 }}
behavior={(Platform.OS === 'ios') ? 'padding' : null}
enabled
keyboardVerticalOffset={Platform.select({ ios: 80, android: 500 })}>
<StatusBar style="light"/>
<ScrollView>
<Container style={{ backgroundColor: commonColor.backgroundColor }}>
<Content padder>
<Card style={{ marginTop: 10, backgroundColor: commonColor.backgroundColor }}>
<View padder>
{error && <View style={{ margin: 10 }}><Messages message={error}/></View>}
{success &&
<View style={{ margin: 10 }}><Messages type="success" message={success}/></View>}
<Form>
<Item floatingLabel style={{ margin: 15 }}>
<Label style={{ color: '#fff', fontFamily: 'Montserrat' }}>
{i18n.t('login.fields.firstName')}
</Label>
<Input
disabled={loading}
style={{ color: '#fff', fontFamily: 'Montserrat' }}
onChangeText={v => this.handleChange('firstName', v)}
/>
</Item>
<Item floatingLabel style={{ margin: 15 }}>
<Label style={{ color: '#fff', fontFamily: 'Montserrat' }}>
{i18n.t('login.fields.lastName')}
</Label>
<Input
disabled={loading}
style={{ color: '#fff', fontFamily: 'Montserrat' }}
onChangeText={v => this.handleChange('lastName', v)}
/>
</Item>
<Item floatingLabel style={{ margin: 15 }}>
<Label style={{ color: '#fff', fontFamily: 'Montserrat' }}>
{i18n.t('login.fields.email')}
</Label>
<Input
disabled={loading}
style={{ color: '#fff', fontFamily: 'Montserrat' }}
autoCapitalize="none"
keyboardType="email-address"
onChangeText={v => this.handleChange('email', v)}
/>
</Item>
<Item floatingLabel style={{ margin: 15 }}>
<Label style={{ color: '#fff', fontFamily: 'Montserrat' }}>
{i18n.t('login.fields.password')}
</Label>
<Input
disabled={loading}
style={{ color: '#fff', fontFamily: 'Montserrat' }}
secureTextEntry
onChangeText={v => this.handleChange('password', v)}
/>
</Item>
<Item floatingLabel style={{ margin: 15 }}>
<Label style={{ color: '#fff', fontFamily: 'Montserrat' }}>
{i18n.t('login.fields.confirmPassword')}
</Label>
<Input
disabled={loading}
style={{ color: '#fff', fontFamily: 'Montserrat' }}
secureTextEntry
selectionColor={'white'}
onChangeText={v => this.handleChange('password2', v)}
/>
</Item>
<Spacer size={40}/>
<ButtonH2t text={'login.signUp'} loading={loading} onPress={this.handleSubmit}/>
</Form>
</View>
</Card>
</Content>
</Container>
</ScrollView>
</KeyboardAvoidingView>
);
}
Example #9
Source File: Login.js From expo-ticket-app with MIT License | 4 votes |
render () {
const { loading, error, success } = this.props;
const { email } = this.state;
return (
<KeyboardAvoidingView
style={{ backgroundColor: commonColor.backgroundColor, flex: 1 }}
behavior={(Platform.OS === 'ios') ? 'padding' : null}
enabled
keyboardVerticalOffset={Platform.select({ ios: 80, android: 500 })}>
<StatusBar style="light"/>
<ScrollView>
<Container style={{ backgroundColor: commonColor.backgroundColor }}>
<Content padder>
<Spacer size={60}/>
<Text style={{
flex: 1,
fontSize: 75,
fontWeight: '400',
fontFamily: 'Montserrat_Bold',
color: 'white',
textAlign: 'center',
}}>
{'H2T.'}
</Text>
<Spacer size={60}/>
<Card style={{ backgroundColor: commonColor.backgroundColor }}>
{error && <View style={{ margin: 10 }}><Messages message={error}/></View>}
{success &&
<View style={{ margin: 10 }}><Messages type="success" message={success}/></View>}
<Form>
<Item floatingLabel style={{ margin: 15 }}>
<Label style={{
color: '#fff',
fontFamily: 'Montserrat',
}}>{i18n.t('login.fields.email')}</Label>
<Input
style={{ color: '#fff', fontFamily: 'Montserrat' }}
autoCapitalize="none"
value={email}
keyboardType="email-address"
disabled={loading}
returnKeyType={'next'}
onChangeText={v => this.handleChange('email', v)}
onSubmitEditing={() => { this.focusTheField('field2'); }}
blurOnSubmit={false}
/>
</Item>
<Item floatingLabel style={{ margin: 15 }}>
<Label style={{
color: '#fff',
fontFamily: 'Montserrat',
}}>{i18n.t('login.fields.password')}</Label>
<Input
getRef={input => { this.inputs['field2'] = input; }}
style={{ color: '#fff', fontFamily: 'Montserrat' }}
secureTextEntry
disabled={loading}
returnKeyType={'go'}
onChangeText={v => this.handleChange('password', v)}
onSubmitEditing={this.handleSubmit}
/>
</Item>
<Spacer size={20}/>
<ButtonH2t text={'login.connect'} loading={loading} onPress={this.handleSubmit}/>
</Form>
<ListItem onPress={Actions.forgotPassword} icon>
<Left>
<Icon style={{ color: 'white' }} name="help-buoy"/>
</Left>
<Body style={{ borderBottomWidth: 0 }}>
<TextI18n style={{ color: 'white' }}>
login.forgotPassword
</TextI18n>
</Body>
</ListItem>
</Card>
</Content>
</Container>
</ScrollView>
</KeyboardAvoidingView>
);
}
Example #10
Source File: FindPeopleScreen.js From SocialApp-React-Native with MIT License | 4 votes |
FindPeopleScreen = (props) => {
const findPeopleUsers = useSelector(state => state.users.findPeople);
const [isLoading, setIsLoading] = useState(false);
const [isRefreshing, setIsRefreshing] = useState(false);
const [error, setError] = useState();
const [searchText, setSearchText] = useState('');
const [data, setData] = useState([]);
const dispatch = useDispatch();
const loadFindPeople = useCallback(async () => {
setError(null);
setIsRefreshing(true);
try {
const result = await dispatch(usersActions.fetchFindPeopleUsers());
let verifiedUsers = result.filter(e => VerifiedUser.verifiedUsersId.includes(e._id));
let otherUsers = result.filter(e => !VerifiedUser.verifiedUsersId.includes(e._id));
let updatedResult = [...verifiedUsers, ...otherUsers];
setData(updatedResult);
} catch (err) {
setError(err.message);
}
setIsRefreshing(false);
}, [dispatch, setIsLoading, setError])
useEffect(() => {
setIsLoading(true);
loadFindPeople()
.then(() => {
setIsLoading(false);
});
}, [dispatch, loadFindPeople])
// useEffect(() => {
// const unsubscribe = props.navigation.addListener('focus', e => {
// setSearchText('');
// setData(findPeopleUsers);
// });
// return () => {
// unsubscribe();
// };
// }, [])
const handleSearchTextChange = (text) => {
setSearchText(text);
if(text !== ''){
let filteredData = []
let currData = findPeopleUsers;
filteredData = currData.filter(item => {
const lc = item.name.toLowerCase();
const lcEmail = item.email.toLowerCase();
text = text.toLowerCase();
return lc.includes(text) || lcEmail.includes(text);
});
setData(filteredData);
} else {
setData(findPeopleUsers);
}
}
const followHandlerForData = (id) => {
//follow handler to remove item from search data i.e. data state
let searchData = data;
searchData = searchData.filter(i => i._id !== id);
setData(searchData);
}
if(error){
return (
<View style={styles.centered} >
<Text>An error occured.</Text>
<Button onPress={loadFindPeople} color={Colors.primary} >
<Text>Try again</Text>
</Button>
</View>
);
}
if(isLoading){
return (
<View style={styles.centered} >
<ActivityIndicator size='large' color={Colors.primary} />
</View>
);
}
return (
<Container style={{ backgroundColor: '#fff' }} >
<Header style={{ backgroundColor: Colors.brightBlue }} searchBar rounded>
<Item>
<Icon name="ios-search" />
<Input
value={searchText}
onChangeText={(text) => handleSearchTextChange(text)}
placeholder={`Search by name or email...`}
/>
<Text>{data.length}</Text>
<Icon name="ios-people" />
</Item>
</Header>
{ data.length === 0 && (
<View style={styles.centered}>
<Text style={{ fontSize: 18, margin: 10 }} >No users found.</Text>
<Text>Either you are already following the user</Text>
<Text>or no user exists with that name.</Text>
</View>
) }
<FlatList
style={styles.list}
refreshing={isRefreshing}
onRefresh={loadFindPeople}
contentContainerStyle={styles.listContainer}
data={data}
horizontal={false}
numColumns={2}
keyExtractor={(item) => {
return item._id;
}}
renderItem={({ item }) => (
<UserList item={item} followHandler={followHandlerForData} />
)}
/>
</Container>
);
}
Example #11
Source File: MakeTransaction.js From web3-react-native with MIT License | 4 votes |
MakeTransaction = ({ onPressSubmit, ...extraProps }) => {
const [toAddress, setToAddress] = useState("0x19e03255f667bdfd50a32722df860b1eeaf4d635");
const [amount, setAmount] = useState("1");
const [units, setUnits] = useState("wei");
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
return (
<Container>
<Content>
<Form>
<Item>
<Label
children="Address:"
/>
<Input
onChangeText={setToAddress}
value={toAddress}
/>
</Item>
<Item
>
<Label
children="Amount:"
/>
<Input
onChangeText={setAmount}
value={amount}
/>
</Item>
<Item
last
>
<Label
children="Units:"
/>
<Picker
onValueChange={setUnits}
selectedValue={units}
>
<Picker.Item label="Wei" value="wei" />
<Picker.Item label="Kwei" value="kwei" />
<Picker.Item label="Mwei" value="mwei" />
<Picker.Item label="Gwei" value="gwei" />
<Picker.Item label="Finney" value="finney" />
<Picker.Item label="Ether" value="eth" />
</Picker>
</Item>
</Form>
<View
style={styles.errorContainer}
>
{(!!error) && (
<Text
style={styles.error}
children={error.message}
/>
)}
</View>
<View
style={styles.buttonContainer}
>
<Button
disabled={loading}
style={styles.button}
onPress={e => Promise
.resolve()
.then(() => [
setLoading(true),
])
.then(() => onPressSubmit(e, toAddress, amount, units))
.then(() => setLoading(false))
.catch(
(e) => {
setError(e);
setLoading(false);
},
)}
primary
rounded
>
{(!!loading) && (
<Spinner
size={20}
/>
)}
<Text
children="Send"
/>
</Button>
</View>
</Content>
</Container>
);
}
Example #12
Source File: RegisterScreen.js From inventory-management-rn with MIT License | 4 votes |
RegisterScreen = ({navigation}) => {
return (
<Container style={{backgroundColor: '#F3F9FB'}}>
<Header style={{ backgroundColor: '#4796BD', flexDirection: 'row', alignItems: 'center' }} androidStatusBarColor="#247095">
<Text style={{ color: '#fff', fontSize: 20 }}>Register</Text>
</Header>
<Content>
<Body>
<Text style={styles.heading}>Register</Text>
<Text
style={{
alignSelf: 'flex-start',
fontSize: 25,
color: '#122E40',
marginLeft: 28,
marginTop: 25,
marginBottom: 10,
}}>
Account
</Text>
<Item floatingLabel style={styles.inputBox}>
<Label style={styles.label}>Full Name</Label>
<Input
style={styles.inputArea}
blurOnSubmit={true}
onChangeText={value => {
setUserEmail(value);
}}
keyboardType="email-address"
autoCapitalize="none"
/>
</Item>
<Item floatingLabel style={styles.inputBox}>
<Label style={styles.label}>Email-id</Label>
<Input
style={styles.inputArea}
blurOnSubmit={true}
onChangeText={value => {
setUserEmail(value);
}}
keyboardType="email-address"
autoCapitalize="none"
/>
</Item>
<Item floatingLabel style={styles.inputBox}>
<Label style={styles.label}>Password</Label>
<Input
style={styles.inputArea}
blurOnSubmit={true}
onChangeText={value => {
setUserPassword(value);
}}
name="password"
secureTextEntry
/>
</Item>
<Item floatingLabel style={styles.inputBox}>
<Label style={styles.label}>Confirm Password</Label>
<Input
style={styles.inputArea}
blurOnSubmit={true}
onChangeText={value => {
setUserEmail(value);
}}
keyboardType="email-address"
autoCapitalize="none"
/>
</Item>
<Text
style={{
alignSelf: 'flex-start',
fontSize: 25,
color: '#122E40',
marginLeft: 28,
marginTop: 25,
marginBottom: 10,
marginBottom: 10,
}}>
Shop Details
</Text>
<Item floatingLabel style={styles.inputBox}>
<Label style={styles.label}>Name</Label>
<Input
style={styles.inputArea}
blurOnSubmit={true}
onChangeText={value => {
setUserEmail(value);
}}
keyboardType="email-address"
autoCapitalize="none"
/>
</Item>
<Item floatingLabel style={styles.inputBox}>
<Label style={styles.label}>Address</Label>
<Input
style={styles.inputArea}
blurOnSubmit={true}
onChangeText={value => {
setUserEmail(value);
}}
keyboardType="email-address"
autoCapitalize="none"
/>
</Item>
<TouchableOpacity
rounded
style={styles.loginButton}
onPress={() => {
navigation.navigate('LoginScreen');
}}>
<Text style={styles.buttonText}>Register</Text>
</TouchableOpacity>
</Body>
</Content>
</Container>
);
}
Example #13
Source File: LoginScreen.js From inventory-management-rn with MIT License | 4 votes |
LoginScreen = ({ navigation }) => {
const [email, setUserEmail] = useState('');
const [password, setUserPassword] = useState('');
const login = () => {
// fetching the token by providing email and password
fetch('http://chouhanaryan.pythonanywhere.com/auth/token/login/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
'email': email,
'password': password
})
})
.then((res) => res.json())
.then(async (data) => {
const token = data.auth_token;
if (token) {
console.log('token is: ' + token);
// storing token in async storage
try {
await AsyncStorage.setItem('auth_key', token);
} catch (error) {
console.log('Token not saved in async storage properly');
console.log(error);
}
// using the token just received to check the info of the current logged in user
fetch('http://chouhanaryan.pythonanywhere.com/auth/users/me/', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Token ${token}`
}
})
.then((res) => res.json())
.then(async (data) => {
// storing is_staff boolean in async storage
try {
await AsyncStorage.setItem('is_staff', data.is_staff.toString());
} catch (error) {
console.log('is_staff not saved in async storage properly');
console.log(error)
}
navigation.replace('Drawer');
})
.catch((err) => {
console.log(err)
})
} else {
Alert.alert('Invalid email or password', 'Please enter correct credentials')
}
})
.catch((err) => console.log(err))
}
return (
<Container style={{ backgroundColor: '#F3F9FB' }}>
<Header style={{ backgroundColor: '#4796BD', flexDirection: 'row', alignItems: 'center' }} androidStatusBarColor="#247095">
<Text style={{ color: '#fff', fontSize: 24 }}>Login</Text>
</Header>
<Content>
<Body>
<Image
style={{
width: 274,
height: 207,
marginVertical: 40,
marginRight: 10,
}}
source={require('../Images/Illustration.png')}
/>
<Item floatingLabel style={styles.inputBox}>
<Label style={styles.label}>Email ID</Label>
<Input
style={styles.inputArea}
blurOnSubmit={true}
onChangeText={value => {
setUserEmail(value);
}}
keyboardType="email-address"
autoCapitalize="none"
/>
</Item>
<Item floatingLabel style={styles.inputBox}>
<Label style={styles.label}>Password</Label>
<Input
style={styles.inputArea}
blurOnSubmit={true}
onChangeText={value => {
setUserPassword(value);
}}
name="password"
autoCapitalize="none"
secureTextEntry
/>
</Item>
{/* <TouchableOpacity
rounded
style={styles.loginButton}
onPress={() => {
Login(email, password);
}}>
<Text style={styles.buttonText}>Login</Text>
</TouchableOpacity> */}
<TouchableOpacity
rounded
style={styles.loginButton}
onPress={() => {
login()
}}>
<Text style={styles.buttonText}>Login</Text>
</TouchableOpacity>
<View style={{ flexDirection: 'row' }}>
<Text style={styles.newUser}>New user ? </Text>
<TouchableOpacity onPress={() => {
navigation.navigate('RegisterScreen');
}} ><Text style={{
fontSize: 18,
textDecorationLine: 'underline',
color: '#9ca2ad',
// borderBottomWidth:1,
// borderBottomColor: 'black',
marginTop: 25,
marginBottom: 10,
marginBottom: 10,
}}>Register </Text></TouchableOpacity>
</View>
</Body>
</Content>
</Container>
);
}
Example #14
Source File: InventoryListScreen.js From inventory-management-rn with MIT License | 4 votes |
InventoryListScreen = ({navigation}) => {
const [inventoryList, setInventoryList] = useState([]);
const [modalVisible, setModalVisible] = useState(false);
const [updateSellPrice, setUpdateSellPrice] = useState('');
const [updateName, setUpdateName] = useState('');
const [upperLimit, setUpperLimit] = useState('');
const [lowerLimit, setLowerLimit] = useState('');
const [updateProd, setUpdateProd] = useState({});
const [limit, setLimit] = useState(8);
const [offset, setOffset] = useState(0);
const [end, setEnd] = useState(0);
const [isLoading, setIsLoading] = useState(true);
const [isSearch, setIsSearch] = useState(false);
useEffect(() => {
getInventoryList(0);
}, []);
const getInventoryList = async offs => {
console.log(offs);
setIsLoading(false);
const auth_key = await AsyncStorage.getItem('auth_key');
fetch(
`http://chouhanaryan.pythonanywhere.com/api/productlist/?limit=${limit}&offset=${offs}`,
{
method: 'GET',
headers: {
Authorization: `Token ${auth_key}`,
},
},
)
.then(res => res.json())
.then(data => {
setEnd(data.count);
console.log(data.previous, 'prev');
if (data.previous != null) {
const tempInventoryList = [...inventoryList, ...data.results];
if (data.results.length !== 0) {
setInventoryList(tempInventoryList);
}
} else {
if (data.results.length !== 0) {
setInventoryList(data.results);
}
}
})
.catch(err => console.log(err));
};
const deleteInventoryItem = async inventoryItem => {
const auth_key = await AsyncStorage.getItem('auth_key');
await fetch(
`http://chouhanaryan.pythonanywhere.com/api/productlist/${
inventoryItem.id
}/`,
{
method: 'DELETE',
headers: {Authorization: `Token ${auth_key}`},
},
)
.then(() => {
setOffset(0);
getInventoryList(0);
console.log('deleted successfully!');
})
.catch(e => {
console.log(e);
});
};
const performSearch = async search => {
console.log(search);
if (isSearch) {
const auth_key = await AsyncStorage.getItem('auth_key');
fetch(
'http://chouhanaryan.pythonanywhere.com/api/prodsearch/?search=' +
search,
{
method: 'GET',
headers: {
Authorization: `Token ${auth_key}`,
},
},
)
.then(response => response.json())
.then(response => {
console.log(response, 'w');
console.log(inventoryList, 'h');
setInventoryList(response);
})
.catch(error => {
console.log(error);
});
}
};
const updateProductPost = async () => {
let formData = new FormData();
const looseVal = updateProd.loose === true ? 'True' : 'False';
formData.append('loose', looseVal);
formData.append('upper', upperLimit);
formData.append('lower', lowerLimit);
formData.append('name', updateName);
formData.append('latest_selling_price', updateSellPrice);
const auth_key = await AsyncStorage.getItem('auth_key');
console.log(formData,"form");
fetch(
`http://chouhanaryan.pythonanywhere.com/api/update/${updateProd.id}/`,
{
method: 'POST',
headers: {
Authorization: `Token ${auth_key}`,
},
body: formData,
},
)
.then(res => res.json())
.then(data => {
console.log(data);
setOffset(0);
getInventoryList(0);
Alert.alert('Success!', 'Product Updated');
})
.catch(err => console.log(err));
setUpdateName('');
setUpdateSellPrice(null);
};
const handleReach = () => {
if (!isSearch) {
false;
const newOff = offset + limit;
if (newOff < end) {
setIsLoading(true);
setOffset(newOff);
console.log(newOff, limit, end);
getInventoryList(newOff);
}
}
};
const onMenuPressed = inventoryItem => {
console.log(inventoryItem,"Item");
Alert.alert(
`${inventoryItem.name} (Qty: ${inventoryItem.quantity})`,
`Rs. ${inventoryItem.avg_cost_price}`,
[
{
text: 'Update',
onPress: () => {
setUpdateProd(inventoryItem);
setUpdateName(inventoryItem.name);
if (inventoryItem.latest_selling_price) {
setUpdateSellPrice(inventoryItem.latest_selling_price.toString());
} else {
setUpdateSellPrice('Not assigned');
}
console.log(inventoryItem.latest_selling_price);
setUpperLimit(inventoryItem.upper_limit.toString());
setLowerLimit(inventoryItem.lower_limit.toString());
setModalVisible(true);
},
},
{
text: 'Delete',
onPress: () => {
deleteInventoryItem(inventoryItem);
},
},
{
text: 'Cancel',
// onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
],
);
};
var radio_props = [
{label: 'Loose', value: updateProd.loose},
{label: 'Packed', value: !updateProd.loose},
];
return (
<Container style={{backgroundColor: '#F3F9FB'}}>
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
Alert.alert('No changes made');
setModalVisible(!modalVisible);
}}>
<View style={styles.centeredView}>
<View style={styles.modalView}>
<Text style={styles.product_titles}>Update Product</Text>
<View style={{alignItems: 'flex-start', marginVertical: 20}}>
<Item floatingLabel style={styles.inputBox}>
<Label style={styles.label}>Product Name</Label>
<Input
style={styles.inputArea}
onChangeText={value => {
setUpdateName(value);
}}
value={updateName}
/>
</Item>
<Item floatingLabel style={styles.inputBox}>
<Label style={styles.label}>Selling Price</Label>
<Input
style={styles.inputArea}
value={updateSellPrice}
onChangeText={value => {
console.log(typeof(value))
setUpdateSellPrice(value);
}}
keyboardType="numeric"
/>
</Item>
</View>
<View style={{paddingLeft: 10}}>
<Text
style={{
marginTop: 10,
marginBottom: 3,
fontSize: 17,
fontWeight: '800',
}}>
Recommended Limit
</Text>
<NumericInput
value={parseInt(upperLimit)}
onChange={value => {
setUpperLimit(value.toString());
}}
totalWidth={150}
totalHeight={35}
minValue={0}
maxValue={99999}
onLimitReached={(isMAx, msg) => console.log(msg)}
step={1}
iconStyle={{fontSize: 15, color: '#434A5E'}}
inputStyle={{fontSize: 18, color: '#434A5E'}}
valueType="real"
borderColor="#C7CBD6"
rightButtonBackgroundColor="#C7CBD6"
leftButtonBackgroundColor="#C7CBD6"
/>
<Text
style={{
marginTop: 20,
marginBottom: 3,
fontSize: 17,
fontWeight: '800',
}}>
Critical Limit
</Text>
<NumericInput
value={parseInt(lowerLimit)}
onChange={value => {
console.log(typeof(value))
setLowerLimit(value.toString());
}}
totalWidth={150}
totalHeight={35}
minValue={0}
maxValue={99999}
onLimitReached={(isMAx, msg) => console.log(msg)}
step={1}
iconStyle={{fontSize: 15, color: '#434A5E'}}
inputStyle={{fontSize: 18, color: '#434A5E'}}
valueType="real"
borderColor="#C7CBD6"
rightButtonBackgroundColor="#C7CBD6"
leftButtonBackgroundColor="#C7CBD6"
/>
</View>
<Text
style={{
marginTop: 30,
fontSize: 17,
fontWeight: '800',
paddingLeft: 10,
}}>
Type
</Text>
<RadioForm
radio_props={radio_props}
labelHorizontal={true}
formHorizontal={true}
buttonColor={'#434A5E'}
labelColor={'#434A5E'}
initial={(updateProd.loose===true)?0:1}
labelStyle={{marginRight: 20}}
style={{paddingLeft: 10, marginTop: 8}}
onPress={value => {
updateProd.loose = value;
setUpdateProd(updateProd);
}}
/>
<TouchableOpacity
style={styles.addEmployeeButton}
// onPress={() => navigation.navigate('AddEmployee')}
onPress={() => {
updateProductPost();
setModalVisible(!modalVisible);
}}>
<Text style={styles.addEmployeeButtonText}>Update</Text>
</TouchableOpacity>
</View>
</View>
</Modal>
<Content>
{/* the entire outerpart */}
<Body style={styles.listContainer}>
{/* the header of table */}
<TextInput
underlineColorAndroid="transparent"
style={styles.inputStyle}
placeholder=" Search Product"
placeholderTextColor="gray"
multiline={false}
onEndEditing={e => {
console.log(e.nativeEvent.text);
if (e.nativeEvent.text === '') {
setOffset(0);
console.log('bb');
getInventoryList(0);
}
}}
onChangeText={search => {
if (search === '') {
setIsSearch(false);
setOffset(0);
console.log('h');
setIsLoading(true);
setInventoryList([]);
getInventoryList(0);
} else {
setIsSearch(true);
setInventoryList([]);
setTimeout(() => {
performSearch(search);
}, 1500);
}
}}
/>
<View style={styles.tableHeader}>
<CardItem
style={{
backgroundColor: 'rgba(255,255,255,0)',
flexDirection: 'row',
justifyContent: 'space-evenly',
paddingLeft: 40,
}}>
<Text style={styles.productNameHeader}>Product</Text>
<Text style={styles.itemsHeader}>Items</Text>
<Text style={styles.priceHeader}>Price</Text>
</CardItem>
</View>
<FlatList
style={styles.flatlist}
data={inventoryList}
extraData={inventoryList}
renderItem={({item}) => (
<InventoryListItem
onMenuPressed={data => onMenuPressed(data)}
item={item}
/>
)}
keyExtractor={item => item.id}
onEndReached={!isSearch && handleReach}
onEndReachedThreshold={!isSearch && 0.2}
ListFooterComponent={() => {
if (isLoading) {
return <ActivityIndicator size="large" color="#828282" />;
}
return null;
}}
/>
</Body>
</Content>
</Container>
);
}
Example #15
Source File: AddEmployee.js From inventory-management-rn with MIT License | 4 votes |
render() {
return (
<Container style={{backgroundColor: '#F3F9FB'}}>
<HeaderView navigation={this.props.navigation} title={'Add Employee'} />
<Content>
<ScrollView>
<Body>
<Text style={styles.heading}>Account</Text>
<Item floatingLabel style={styles.inputBox}>
<Label style={styles.label}>First Name</Label>
<Input
style={styles.inputArea}
onChangeText={value => {
this.setState({fname: value});
}}
/>
</Item>
<Item floatingLabel style={styles.inputBox}>
<Label style={styles.label}>Last Name</Label>
<Input
style={styles.inputArea}
onChangeText={value => {
this.setState({lname: value});
}}
/>
</Item>
<Item floatingLabel style={styles.inputBox}>
<Label style={styles.label}>Email ID</Label>
<Input
style={styles.inputArea}
keyboardType="email-address"
autoCapitalize="none"
onChangeText={value => {
var mailformat = /^\w+([\.-]?\w+)@\w+([\.-]?\w+)(\.\w{2,3})+$/;
this.setState({email: value});
if (value.match(mailformat)) {
this.setState({inval_email: false});
} else {
this.setState({inval_email: true});
}
}}
/>
</Item>
{this.state.inval_email && this.state.email !== '' && (
<Text
style={{
color: 'red',
alignSelf: 'flex-start',
marginLeft: 40,
}}>
Invalid Email
</Text>
)}
<Item floatingLabel style={styles.inputBox}>
<Label style={styles.label}>Password</Label>
<Input
style={styles.inputArea}
secureTextEntry
onChangeText={value => {
this.setState({password: value});
var passw = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
if (value.length >= 8) {
this.setState({inval_pass: false});
} else {
this.setState({inval_pass: true});
}
}}
/>
</Item>
{this.state.inval_pass && this.state.password !== '' && (
<Text
style={{
color: 'red',
alignSelf: 'flex-start',
marginLeft: 40,
}}>
Password should be atleast 8 characters
</Text>
)}
<Item floatingLabel style={styles.inputBox}>
<Label style={styles.label}>Confirm Password</Label>
<Input
style={styles.inputArea}
secureTextEntry
onChangeText={value => {
this.setState({confpass: value});
}}
/>
</Item>
{this.state.inval_confpass && (
<Text
style={{
color: 'red',
alignSelf: 'flex-start',
marginLeft: 40,
}}>
Password not matching!
</Text>
)}
<Item floatingLabel style={styles.inputBox}>
<Label style={styles.label}>Age</Label>
<Input
style={styles.inputArea}
onChangeText={value => {
this.setState({age: value});
}}
/>
</Item>
<Item style={styles.inputBox}>
<Label style={{marginLeft: 28}}>Gender</Label>
<Picker
style={{width: 247, height: 25, marginLeft: 25}}
selectedValue={this.state.gender}
onValueChange={value => {
this.setState({gender: value});
}}>
<Picker.Item label="Male" value="M" />
<Picker.Item label="Female" value="F" />
<Picker.Item label="Others" value="Other" />
</Picker>
</Item>
<RadioForm
radio_props={[
{label: 'Employee', value: false},
{label: 'Manager', value: true},
]}
labelHorizontal={true}
formHorizontal={true}
buttonColor={'#434A5E'}
labelColor={'#434A5E'}
labelStyle={{marginRight: 20}}
style={{paddingLeft: 10, marginTop: 8}}
onPress={value => {
this.setState({is_staff: value});
}}
/>
{/* <Text style={{color: 'red'}}>HEY</Text> */}
<TouchableOpacity
rounded
style={styles.regButton}
onPress={() => {
if (
this.state.email !== '' &&
this.state.password !== '' &&
this.state.age !== '' &&
this.state.lname !== ''
) {
if (
this.state.fname !== '' &&
this.state.password === this.state.confpass
) {
// let formData = new FormData()
// formData.append('email', this.state.email)
// formData.append('password', this.state.password)
// formData.append('first_name', this.state.fname)
// formData.append('last_name', this.state.lname)
// formData.append('is_staff', true)
// formData.append('age', this.state.age)
// formData.append('gender', this.state.gender)
this.buttonPressed();
} else {
this.setState({inval_confpass: true});
}
} else {
Alert.alert('Alert', 'Please enter all the fields');
}
}}>
<Text style={styles.buttonText}>Register</Text>
</TouchableOpacity>
</Body>
</ScrollView>
</Content>
</Container>
);
}
Example #16
Source File: Sell.js From inventory-management-rn with MIT License | 4 votes |
Sell = ({navigation}) => {
const [product, setProduct] = useState([]);
const [selected, setSelected] = useState('key1');
const [list, setProductsList] = useState([]);
const [customerName, setCustomerName] = useState('');
const [phoneNumber, setPhoneNumber] = useState('');
const [address, setAddress] = useState('');
const onPickerValueChange = (item_name, item_index, product_index) => {
setSelected(item_name);
console.log('this is name:', item_name);
console.log('this is index:', item_index);
console.log('which prod no.?:', product_index);
let copy = [...product];
copy[product_index].name = item_name;
console.log(copy);
setProduct(copy);
};
useEffect(() => {
setProduct([{name: 'Pick a value', price: '', amount: ''}]);
apiFetch();
}, []);
const apiFetch = async () => {
const auth_key = await AsyncStorage.getItem('auth_key');
fetch('http://chouhanaryan.pythonanywhere.com/api/productlist/', {
method: 'GET',
headers: {
Authorization: `Token ${auth_key}`,
},
})
.then(res => res.json())
.then(data => {
console.log(data);
setProductsList(data.results);
})
.catch(err => console.log(err));
};
const sellprod = async () => {
await product.forEach(async product => {
const formData = new FormData();
formData.append('name', product.name);
formData.append('quantity', parseInt(product.amount));
formData.append('latest_selling_price', parseFloat(product.price));
var myHeaders = new Headers();
const auth_key = await AsyncStorage.getItem('auth_key');
myHeaders.append('Authorization', `Token ${auth_key}`);
fetch('http://chouhanaryan.pythonanywhere.com/api/sell/', {
method: 'POST',
headers: myHeaders,
body: formData,
redirect: 'follow',
})
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
});
};
return (
<Container style={{backgroundColor: '#F3F9FB'}}>
<Content>
<Body>
<Text style={styles.heading}>Sell Items</Text>
{/* separator line above name, phone no. and address fields */}
<View style={{ flex: 1, flexDirection: 'row', marginBottom: 10 }}>
<View
style={{
borderColor: '#0004',
borderWidth: 1,
width: '90%',
alignSelf: 'center',
borderRadius: 2,
marginBottom: -10,
marginTop: 5,
}}
/>
</View>
{/* customer name */}
<Item floatingLabel style={styles.inputBox}>
<Label style={styles.label}>Customer Name</Label>
<Input
style={styles.inputArea}
value={customerName}
onChangeText={value => setCustomerName(value)}
/>
</Item>
{/* phone number */}
<Item floatingLabel style={styles.inputBox}>
<Label style={styles.label}>Phone number</Label>
<Input
style={styles.inputArea}
keyboardType='number-pad'
value={phoneNumber}
onChangeText={value => setPhoneNumber(value)}
/>
</Item>
{/* address */}
<Item floatingLabel style={styles.inputBox}>
<Label style={styles.label}>Address</Label>
<Input
style={styles.inputArea}
value={address}
onChangeText={value => setAddress(value)}
/>
</Item>
{product.map((product_item, product_index) => {
return (
<View
key={product_index}
style={{width: Dimensions.get('window').width}}>
{/* for the separating line */}
<View
style={{
borderColor: '#0004',
borderWidth: 1,
width: '90%',
alignSelf: 'center',
borderRadius: 2,
marginBottom: -10,
marginTop: 5,
}}
/>
<Text style={styles.product_titles}>
Product {product.length == 1 ? '' : product_index + 1}
</Text>
<View
style={{
justifyContent: 'space-evenly',
flexDirection: 'row',
}}>
{/* <Label style={styles.label}>Product Name</Label> */}
<Text style={[styles.label, {alignSelf: 'center'}]}>
Product Name
</Text>
<Form
style={{
borderWidth: 1,
borderColor: '#0006',
flex: 0.8,
borderRadius: 5,
}}>
<Picker
note
mode="dropdown"
selectedValue={product[product_index].name}
onValueChange={(item_name, item_index) => {
onPickerValueChange(
item_name,
item_index,
product_index,
);
}}>
{/* <Picker.Item label='plz pick' value={-1} /> */}
{list.map((picker_item, picker_index) => (
<Picker.Item
key={picker_index}
// label={picker_item.name + " ("+picker_item.quantity+")"}
label={picker_item.name}
value={picker_item.name}
/>
))}
</Picker>
</Form>
</View>
<Item floatingLabel style={styles.inputBox}>
<Label style={styles.label}>Price</Label>
<Input
style={styles.inputArea}
keyboardType="numeric"
onChangeText={value =>
(product[product_index].price = parseFloat(value.trim()))
}
/>
</Item>
<Item floatingLabel style={styles.inputBox}>
<Label style={styles.label}>No. of Items</Label>
<Input
style={styles.inputArea}
keyboardType="numeric"
onChangeText={value =>
(product[product_index].amount = parseInt(value.trim()))
}
/>
</Item>
</View>
);
})}
<TouchableOpacity
onPress={() => {
console.log(product);
if (
product[product.length - 1].name &&
product[product.length - 1].price &&
product[product.length - 1].amount
) {
let copy = [...product];
copy.push({name: '', price: '', amount: ''});
setProduct(copy);
} else {
Alert.alert(
`Please fill all details for product ${product.length}`,
);
}
}}
style={styles.addButton}>
<Icon name="plus" color="#4796BD" size={25} style={styles.icon} />
<Text style={styles.addButtonText}>Add Product</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={async () => {
let all_unique = true;
console.log('product', product);
console.log('list', list);
if (product.length != 1) {
for (let i = 0; i < product.length; i++) {
for (let j = i + 1; j < product.length; j++) {
if (product[i].name == product[j].name) {
all_unique = false;
break;
}
}
}
}
if (!all_unique) {
console.log('same names');
Alert.alert('please select all unique items');
} else if (
product[product.length - 1].name == '' ||
product[product.length - 1].price == '' ||
product[product.length - 1].amount == ''
) {
Alert.alert(
`Please fill valid details for product ${product.length}`,
);
} else {
let enough_stock = true;
let shortage_products = [];
for (let i = 0; i < product.length; i++) {
const product_object = product[i];
for (let j = 0; j < list.length; j++) {
const list_item_object = list[j];
if (
product_object.name == list_item_object.name &&
product_object.amount > list_item_object.quantity
) {
shortage_products.push(product_object.name);
enough_stock = false;
break;
}
}
}
if (!enough_stock) {
Alert.alert(
`Not enough stock in inventory for ${shortage_products}`,
);
} else {
console.log('finally sold!!');
await sellprod();
await setProduct([]);
await setProduct([{name: '', price: '', amount: ''}]);
await setAddress();
await setAddress('');
await setCustomerName();
await setCustomerName('');
await setPhoneNumber();
await setPhoneNumber('')
}
}
}}
style={styles.sellButton}>
<Text style={styles.sellButtonText}>Sell</Text>
</TouchableOpacity>
</Body>
</Content>
</Container>
);
}
Example #17
Source File: Buy.js From inventory-management-rn with MIT License | 4 votes |
Buy = ({ navigation }) => {
const [product, setProduct] = useState([]);
const [date_array, setDate_array] = useState([]);
const [show, setShow] = useState(false);
const [curr_ind, setCurr_ind] = useState(0);
const [customerName, setCustomerName] = useState('');
const [phoneNumber, setPhoneNumber] = useState('');
const [address, setAddress] = useState('');
useEffect(() => {
setProduct([{ name: '', price: 0, amount: 0, expiry: '' }]);
setDate_array([new Date()])
}, []);
const buyprod = async () => {
product.forEach(async product => {
const formdata = new FormData();
formdata.append("name", product.name);
formdata.append("avg_cost_price", product.price);
formdata.append("quantity", product.amount);
formdata.append("expiry", product.expiry);
let myHeaders = new Headers();
const auth_key = await AsyncStorage.getItem('auth_key');
myHeaders.append("Authorization", `Token ${auth_key}`);
fetch('http://chouhanaryan.pythonanywhere.com/api/buy/', {
method: 'POST',
headers: myHeaders,
body: formdata,
redirect: 'follow',
})
.then(res => console.log(res))
.catch(err => console.log(err));
});
};
const set_date = (e) => {
setShow(false);
let date_array_copy = [...date_array];
let product_copy = [...product];
const date = new Date(e.nativeEvent.timestamp)
date_array_copy[curr_ind] = date;
setDate_array(date_array_copy);
if (date == 'Invalid Date') {
product_copy[curr_ind].expiry = 'Choose a date and press OK';
setProduct(product_copy);
} else {
const month = date.toLocaleDateString().split('/')[0];
const day = date.toLocaleDateString().split('/')[1];
const year = date.toDateString().split(' ')[3];
const final_date = year + '-' + month + '-' + day;
product_copy[curr_ind].expiry = final_date;
setProduct(product_copy);
}
}
return (
<Container style={{ backgroundColor: '#F3F9FB' }}>
<ScrollView>
<Body>
<Text style={styles.heading}>Buy Items</Text>
{/* separator line above name, phone no. and address fields */}
<View style={{ flex: 1, flexDirection: 'row', marginBottom: 10 }}>
<View
style={{
borderColor: '#0004',
borderWidth: 1,
width: '90%',
alignSelf: 'center',
borderRadius: 2,
marginBottom: -10,
marginTop: 5,
}}
/>
</View>
{/* customer name */}
<Item floatingLabel style={styles.inputBox}>
<Label style={styles.label}>Customer Name</Label>
<Input
style={styles.inputArea}
value={customerName}
onChangeText={value => setCustomerName(value)}
/>
</Item>
{/* phone number */}
<Item floatingLabel style={styles.inputBox}>
<Label style={styles.label}>Phone number</Label>
<Input
style={styles.inputArea}
keyboardType='number-pad'
value={phoneNumber}
onChangeText={value => setPhoneNumber(value)}
/>
</Item>
{/* address */}
<Item floatingLabel style={styles.inputBox}>
<Label style={styles.label}>Address</Label>
<Input
style={styles.inputArea}
value={address}
onChangeText={value => setAddress(value)}
/>
</Item>
{product.map((item, index) => {
return (
<View key={index} style={{ width: Dimensions.get('window').width }}>
{/* for the separating line */}
<View
style={{
borderColor: '#0004',
borderWidth: 1,
width: '90%',
alignSelf: 'center',
borderRadius: 2,
marginBottom: -10,
marginTop: 5,
}}
/>
{/* Product title */}
<Text style={styles.product_titles}>
Product {product.length == 1 ? '' : index + 1}
</Text>
{/* Product name input */}
<Item floatingLabel style={styles.inputBox}>
<Label style={styles.label}>Product Name</Label>
<Input
placeholder={product[index].name}
style={styles.inputArea}
onChangeText={value => (product[index].name = value.trim())}
/>
</Item>
{/* Price input */}
<Item floatingLabel style={styles.inputBox}>
<Label style={styles.label}>Price</Label>
<Input
style={styles.inputArea}
keyboardType="numeric"
onChangeText={value =>
(product[index].price = parseFloat(value.trim()))
}
/>
</Item>
{/* Quantity input */}
<Item floatingLabel style={styles.inputBox}>
<Label style={styles.label}>No. of Items</Label>
<Input
style={styles.inputArea}
keyboardType="numeric"
onChangeText={value =>
(product[index].amount = parseInt(value.trim()))
}
/>
</Item>
{/* Expiry date text */}
<View style={{ flexDirection: 'row', flex: 1 }}>
<View style={styles.dateMainView}>
<Text
style={{
marginLeft: 4,
fontSize: 16,
marginTop: 17,
color: 'black',
}}>
Expiry: {product[index].expiry}
</Text>
</View>
<TouchableOpacity onPress={() => {
setCurr_ind(index);
setShow(true)
}}>
<Icon
name="calendar"
color="#4796BD"
size={30}
style={{
marginLeft: -10,
flex: 1,
marginRight: 30,
marginTop: 20,
}}
/>
</TouchableOpacity>
</View>
{/* Date display */}
<View>
<View>
{show && (
<DateTimePicker
testID="dateTimePicker"
value={new Date()}
mode='date'
is24Hour={true}
display="default"
onChange={(e) => set_date(e)}
/>
)}
</View>
</View>
</View>
);
})}
<TouchableOpacity
onPress={() => {
if (
product[product.length - 1].name &&
product[product.length - 1].price &&
product[product.length - 1].amount &&
product[product.length - 1].expiry.length === 10 // length should be 10 because for date, we have format YYYY-MM-DD, and the length of the string is thus 10
) {
let copy = [...product];
copy.push({ name: '', price: 0, amount: 0, expiry: '' });
setProduct(copy);
let dates_copy = [...date_array];
dates_copy.push(new Date());
setDate_array(dates_copy);
} else {
Alert.alert(
`Please fill all details for product ${product.length}`,
);
}
}}
style={styles.addButton}>
<Icon name="plus" color="#4796BD" size={25} style={styles.icon} />
<Text style={styles.addButtonText}>Add Product</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={async () => {
let can_buy = true;
let incomplete_product_index = 0;
for (let i = 0; i < product.length; i++) {
if (
product[i].name == '' ||
product[i].price == 0 ||
product[i].amount == 0 ||
product[i].expiry.length !== 10
) {
can_buy = false;
incomplete_product_index = i + 1;
break;
}
}
if (!can_buy) {
Alert.alert(
`Please fill valid details for product ${incomplete_product_index}`,
);
} else {
await buyprod();
await setProduct([]);
await setProduct([{ name: '', price: 0, amount: 0, expiry: '' }]);
await setDate_array([new Date()]);
await setAddress();
await setAddress('');
await setCustomerName();
await setCustomerName('');
await setPhoneNumber();
await setPhoneNumber('')
}
}}
style={styles.buyButton}>
<Text style={styles.buyButtonText}>Buy</Text>
</TouchableOpacity>
</Body>
</ScrollView>
</Container>
);
}