email Validation on React native with tcomb package - react-native

i want to validate email in react native, but it still didn't work for me
this is my code
const Email = t.subtype(t.Str, (email) => {
const reg = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return reg.test(email);
});
componentWillReceiveProps(newProps) {
let data_cars = this.carOptions(newProps.cars);
let data_year = this.yearCarOptions();
if (Object.keys(newProps.car_brand).length && Object.keys(newProps.user).length) {
let form = t.struct({
name: t.String,
email: Email,
phone: t.Number,
plate: t.enums(data_cars),
carbrand: t.enums(newProps.car_brand),
carclass: t.enums(newProps.car_class),
year: t.enums(data_year),
})
this.setState({ form })
this.setState({ value: {
name : newProps.user.name,
email : newProps.user.email,
phone : newProps.user.phone
} });
}
}
const options = {
auto: 'none',
fields: {
name: {
label: 'Name',
placeholder: 'name',
placeholderTextColor: 'rgba(255,255,255,0.6)',
error: 'enter your name'
},
email: {
label: 'Email',
placeholder: 'e.g: abc#gmail.com',
placeholderTextColor: 'rgba(255,255,255,0.6)',
error: 'Insert a valid email'
},
},
stylesheet: formStyle.underline(colors.dark),
};
const Form = t.form.Form;
if i submitting the data, it could still return not an email
like this
how do i achieve to validate email?

Use code like below
validate = (text) => {
console.log(text);
let reg = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (reg.test(text) === false) {
console.log("Email is Not Correct");
this.setState({ email: text })
return false;
}
else {
this.setState({ email: text })
console.log("Email is Correct");
}
}
<TextInput
placeholder="Email ID"
onChangeText={(text) => this.validate(text)}
value={this.state.email}
/>
onPressOfButton = () => {
this.validate(this.state.email);
}

Related

TypeError: this.props.navigation.getParam is not a function while passing parameter react native

I am using navigation version 5 and there are two screen home and search screen, i want to copy value search screen to home screen getting error TypeError: props.navigation.getParam is not a function.
Search Screen
async savechange() {
this.props.navigation.navigate('HomeScreen', { city: this.state.text })
await AsyncStorage.setItem("cityname", this.state.text)
}
async clicklist(name) {
this.setState({ text: name })
await AsyncStorage.setItem("cityname", this.state.text)
this.props.navigation.navigate('HomeScreen', { city: this.state.text })
}
Home Screen
async getWeather() {
// cityname = "london"
cityname = this.props.navigation.getparam('cityname','london')
console.log("CityName ->>" + cityname)
KeyID = '...'
fetch(`http://api.openweathermap.org/data/2.5/weather?q=${cityname}&units=metric&APPID=${KeyID}`)
.then(result => result.json())
.then(data => {
// console.log(data)
this.setState({
info: {
name: data.name,
temp: data.main.temp,
country: data.sys.country,
humidity: data.main.humidity,
description: data.weather[0].description,
icon: data.weather[0].icon
}
})
}).catch(err => {
Alert.alert("Error" + err.message + "Please connect to internet", [{ text: "Ok" }])
})
}
If you are using react-navigation V5 use:
props.route.params
For example:
props.navigation.navigate("ScreenB", {title: "Hello World"});
_________________________________________________________________
export default function ScreenB(props){
useEffect(() => {
setTitle(props.route.params.title);
},[])
...
}

React Native app closing after Razorpay sucessCallBack()

The entire payment is done properly. Here is the code:
'''
const that = this;
function makePayment(){
var options = {
description: 'Bank payment',
currency: 'INR',
key: 'xxx',
amount: that.state.amount_razorpay,
name: 'xyz',
order_id: that.state.id,
prefill: {
email: 'xxx#gmail.con',
contact: '123',
name: 'XYZ'
},
theme: {color: '#53a20e'}
}
RazorpayCheckout.open(options,razr_successCallback,razr_errorCallback)
}
function razr_successCallback(data){
console.log('success',data.razorpay_payment_id);
that.setState({razr_Status:"SUCCESS"});
that.setState({razr_txnId:data.razorpay_payment_id});
// that.props.navigation.navigate('Secured');
}
function razr_errorCallback(data){
console.log('failure',data);
}
'''
The console at razr_successCallback() is giving proper result {"razorpay_payment_id": "pay_Eby2FPTakKuSrz"} but the app is exiting immediately without navigation back to the payment page. I even tried that.props.navigation.navigate('Secured') but still the payment page is not redirected. What is the problem?
Edit 1 :
'''
RazorpayCheckout.open(options)
.then(async data =>
await razr_successCallback(data);
})
.catch(error => {
console.log("payment error", error);
});
async function razr_successCallback(data){
console.log(data);
that.props.navigation.goBack();
}
'''
Still facing same problem
This returns a promise, try it this way :
RazorpayCheckout.open(options)
.then(data => {
// handle success
razr_successCallback(data);
})
.catch(error => {
console.log("payment error", error);
});
in My Case :
const razorpayOpenModal = (razorpay_id, currency) => {
let options = {
description: "Credits towards consultation",
image: images.logo,
currency: currency,
order_id: razorpay_id,
key: RAZOPAY_KEY,
amount: totalAmount * 100,
external: {
wallets: ["paytm"]
},
name: "MyApp.jo",
prefill: {
email: userFromCtxt && userFromCtxt.email,
contact: userFromCtxt && userFromCtxt.phone,
name: userFromCtxt
? userFromCtxt.first_name + " " + userFromCtxt.last_name
: ""
},
theme: { color: color.primaryHeaderColor }
};
RazorpayCheckout.open(options)
.then(async data => {
setPaymentId(data.razorpay_payment_id);
await setShowModel(true);
})
.catch(error => {
console.log("payment error", error)
});
};
and then on model :
<MessageModal
button={true}
primaryMessage={primaryText}
secondaryMessage={secondaryText}
visible={modalVisible}
transactionResp={transactionResp}
closeModal={async () => {
setModalVisible(false);
await props.navigation.navigate("Home");
}}
buttonText={"Continue"}
image={transactionResp ? images.success : null}
onPressButton={async () => {
setModalVisible(false);
await props.navigation.navigate("Home");
}}
/>

Cannot read property 'id' of undefined. Variable 'id' has coerced Null value for NonNull type 'ID!'

I am using react native gifted chat and I am trying to figure out how to set _id, text, createdAt, userid, and name to the parameters of my mutation. I have been getting the following errors variable id has coerced null value or cannot read property 'id' is undefined. The main question I have is what to set messageid and messagetext to. I am using react native gifted chat with AWS.
export const createMessage = `mutation createMessage($id: ID! $groupchatid: ID! $message: String! $createdUser: String! $createdTime: String!) {
createMessage(input:{ id:$id groupchatid:$groupchatid, message:$message, createdUser: $createdUser createdTime: $createdTime}) {
id
groupchatid
message
createdUser
createdTime
}
}`;
const user = Auth.currentAuthenticatedUser();
this.setState({ username: user.username});
}
MessagesMutation = async () => {
const AddMessage = { message: this.state.messages, createdUser: this.state.username, groupchatid: this.state.groupchatname };
const newGroupChatMessage = await API.graphql(graphqlOperation(createMessage, AddMessage));
console.log(JSON.stringify(newGroupChatMessage));
};
componentWillMount() {
this.setState({
messages: [
{
_id: id,
text: message,
createdAt: new Date(),
user: {
_id: createdUser,
name: createdUser,
avatar: 'https://placeimg.com/140/140/any',
},
},
],
})
}
componentDidMount() {
const { navigation } = this.props;
const value = navigation.getParam('value')
this.setState({groupchatname: value})
}
onSend(messages = []) {
this.setState(previousState => ({
messages: GiftedChat.append(previousState.messages, messages),
}))
}
render(){
const { groupchatname} = this.state;
return (
<SafeAreaView style={{ flex: 1 }}>
<Header style={styles.headerColor}>
<Text style={styles.text}>{groupchatname}</Text>
</Header>
<GiftedChat
messages={this.state.messages}
renderUsernameOnMessage={true}
onSend={messages => this.onSend(messages), this.MessagesMutation}
user={{
_id: this.user,
name: this.user,
avatar: 'https://placeimg.com/140/140/any'
}}```
You 've defined id as a parameter
createMessage($id: ID! $groupchatid: ID! $message: String! $createdUser: String!
$createdTime: String!)
and have forgotten to pass an argument
const AddMessage = {
id:"valu...." //here
message: this.state.messages,
createdUser: this.state.username,
groupchatid: this.state.groupchatname
};

Sending field input to firebase from state

I'm currently working on app that has ability to add new tasks, assign them to others and choose due date.
I'd like to start sending the assignee and due date of the task to my firebase.
This is my dropdowncomponent:
class DropdownComponent extends Component {
constructor(props){
super(props);
this.state = {
assignee: '',
data: [{
value: 'apple',
}, {
value: 'lemon',
}, {
value: 'orange',
}, {
value: 'banana',
}, {
value: 'watermelon',
}],
value: ''
}
}
handleAssigneePicked = value => {
this.setState({ assignee: value })
console.log("Assignee " + value)
};
render() {
return (
<Dropdown
data={this.state.data}
value={this.state.assignee}
onChangeText={this.handleAssigneePicked}
/>
);
}
}
And this is how I render datepicker
<DateTimePicker
isVisible={this.state.isDateTimePickerVisible}
onConfirm={this.handleDatePicked}
onCancel={this.hideDateTimePicker}
/>
handleDatePicked = date => {
console.log("A date has been picked: ", date);
this.hideDateTimePicker();
this.setState({ selectedDate: moment().format('D MMM DD YYYY HH:MM')})
};
When I choose an item from dropdown, it also console logs the corresponding value, meaning the state changed, no issues there.
However, if i'm trying to send that information to firebase, using code below:
const SaveNewTask = (name, body) => {
const { currentUser } = firebase.auth();
// eslint-disable-next-line no-undef
// eslint-disable-next-line no-unused-expressions
!!name && !!body
?
firebase
.database()
.ref(`/users/${currentUser.uid}/tasks`)
.push({
name, body, assignee, selectedDate, timestamp: Date.now(), completed: false, archived: false
})
// eslint-disable-next-line no-undef
: alert('All fields are required.');
};
But I'm getting can't find variable: assignee and selectedDate, can I get some help with this? I must be missing something little.
Looks like you forgot to pass these params to action
const SaveNewTask = (name, body, assignee, selectedDate) => {
const { currentUser } = firebase.auth();
!_.isEmpty(name) && !_.isEmpty(body) && !_.isEmpty(assignee) && selectedDate != undefined
?
firebase
.database()
.ref(`/users/${currentUser.uid}/tasks`)
.push({
name, body, assignee, selectedDate, timestamp: Date.now(), completed: false, archived: false
})
: alert('All fields are required.');
};
you can use _.isEmpty() by lodash

can't set response from api to messages array of GiftedChat

I am new to react native. I am currently developing a messaging app.
I have used npm-giftedChat for UI & functionalities. The problem is I need to get the response from api & set it to the messages array of giftedchat. I receive data from API and while I set it to messages array it loops over data and renders only the last data in that array.
Any help would be appreciated.I have added my code here
Please find where I am going wrong?
componentWillMount() {
var arrMsg = [];
var data = params.data
for(let i = 0; i < data.Replies.length ; i++){
var obj = {
_id: data.To._id,
text: data.Replies[i].Reply,
createdAt: data.Replies[i].CreatedDate,
user: {
_id: data.From._id,
name: 'React Native',
avatar: data.From.Profile.DisplayPicture
},
image: '',
}
arrMsg.push(obj)
}
this.setState({messages: arrMsg})
}
Sample output
My self also facing same issues..
setting is very important in gifted chat..
so try to use following in ur code,i have edited same like your code.if any queries let me know thanks.
for (let i = 0; i < data.Replies.length; i++) {
console.log(data.Replies[i].CreatedDate);
debugger
var id = data.From._id
if (data.To.id == UserID) {
id = this.state.userID
}
const obj = {
_id: Math.round(Math.random() * 1000000),
text: data.Replies[i].Reply,
createdAt: data.Replies[i].CreatedDate,
user: {
_id: id,
name: 'React Native',
avatar: data.From.Profile.DisplayPicture
},
image: '',
}
arrMsg.push(obj);
};
this.setState((previousState) => {
return {
messages: GiftedChat.append(previousState.messages, arrMsg)
};
});
I wrote a gist here on how to add a web socket listening to a rails channel to a react native chat screen + Gifted Chat
// chat.js
import React, { Component } from 'react';
import {
Text,
View,
StyleSheet,
TouchableHighlight,
Dimensions,
AppState,
AsyncStorage,
Alert
} from 'react-native';
import {
GiftedChat,
Actions,
Bubble,
SystemMessage
} from 'react-native-gifted-chat';
import axios from 'axios';
import ActionCable from 'react-native-actioncable';
import { yourRootUrl, websocketUrl } from '../config/constants';
class Chat extends Component {
state = {
messages: [],
client: '',
accessToken: '',
expiry: '',
uid: '',
userId: ''
}
componentDidMount() {
AsyncStorage.multiGet(
['client', 'expiry',
'access_token', 'uid',
'account_balance', 'userId'
]
)
.then((result) => {
this.setState({
client: result[0][1],
expiry: result[1][1],
accessToken: result[2][1],
uid: result[3][1],
userId: result[5][1]
});
})
.then(() => {
this.getPreviousMessages();
})
.then(() => {
this.createSocket();
})
.catch(() => {
//error logic
});
}
getPreviousMessages() {
//when we open the chat page we should load previous messages
const { chatId } = this.props.navigation.state.params;
const { client, accessToken, uid, userId } = this.state;
const url = yourRootUrl + '/chats/' + chatId;
const headers = {
'access-token': accessToken,
client,
expiry,
uid
};
axios.get(url, { headers })
.then((response) => {
/*
lets construct our messages to be in
same format as expected by GiftedChat
*/
const allMessages = [];
response.data.included.forEach((x) => {
if (x.attributes.system) {
const sysMessage = {
_id: x.id,
text: x.attributes['message-text'],
createdAt: new Date(x.attributes['created-at']),
system: true
};
allMessages.push(sysMessage);
} else {
const userMessage = {
_id: x.id,
text: x.attributes['message-text'],
createdAt: new Date(x.attributes['created-at']),
user: {
_id: x.attributes['sender-id'],
avatar: x.attributes['sender-avatar'],
},
image: x.attributes.image,
};
allMessages.push(userMessage);
}
});
if (allMessages.length === response.data.included.length) {
//lets sort messages according to date created
const sortAllMessages = allMessages.sort((a, b) =>
b.createdAt - a.createdAt
);
this.setState((previousState) => {
return {
messages: GiftedChat.append(previousState.messages, sortAllMessages)
};
});
}
})
}
createSocket() {
//assuming you have set up your chatchannel in your rails backend
const { client, accessToken, uid, userId } = this.state;
const { chatId } = this.props.navigation.state.params; //using react-navigation
const WEBSOCKET_HOST = websocketUrl +
'access-token=' + accessToken + '&client=' +
client + '&uid=' + uid;
const cable = ActionCable.createConsumer(WEBSOCKET_HOST);
this.channel = cable.subscriptions.create(
{
channel: 'ChatChannel',
id: chatId
}, {
received: (data) => {
console.log('Received Data:', data);
if ((data.message.sender_id !== parseInt(userId))
|| (data.message.image !== null)) {
//ensuring you do not pick up your own messages
if (data.message.system === true) {
const sysMessage = {
_id: data.message.id,
text: data.message.message_text,
createdAt: new Date(data.message.created_at),
system: true
};
this.setState((previousState) => {
return {
messages: GiftedChat.append(previousState.messages, sysMessage)
};
});
} else {
const userMessage = {
_id: data.message.id,
text: data.message.message_text,
createdAt: new Date(data.message.created_at),
user: {
_id: data.message.sender_id,
avatar: data.message.sender_avatar,
},
image: data.message.image,
};
this.setState((previousState) => {
return {
messages: GiftedChat.append(previousState.messages, userMessage)
};
});
}
}
},
connected: () => {
console.log(`Connected ${chatId}`);
},
disconnected: () => {
console.warn(`${chatId} was disconnected.`);
},
rejected: () => {
console.warn('connection rejected');
},
});
}
onSend(messages = []) {
const { chatId } = this.props.navigation.state.params;
const { client, accessToken, uid, userId } = this.state;
this.setState((previousState) => {
return {
messages: GiftedChat.append(previousState.messages, messages)
};
});
messages.forEach((x) => {
const url = yourRootUrl + '/messages';
const headers = {
'access-token': accessToken,
client,
expiry,
uid
};
const data = {
chat_id: chatId,
sender_id: userId,
sender_name: name,
message_text: x.text,
image: x.image
};
/*
send the message to your rails app backend
hopefully you have a callback in your model like
after_create :broadcast_message
then broadcast to the chat channel from your rails backend
*/
axios.post(url, data, { headers })
.then(response => console.log(response));
});
}
renderBubble(props) {
return (
<Bubble
{...props}
wrapperStyle={{
left: {
backgroundColor: '#f9f9f9',
}
}}
/>
);
}
renderSystemMessage(props) {
return (
<SystemMessage
{...props}
containerStyle={{
marginBottom: 15,
}}
textStyle={{
fontSize: 14,
textAlign: 'center'
}}
/>
);
}
render() {
return (
<GiftedChat
messages={this.state.messages}
onSend={message => this.onSend(message)}
user={{
_id: parseInt(userId)
}}
renderBubble={this.renderBubble}
renderSystemMessage={this.renderSystemMessage}
/>
);
}
}