This time I have another issue when trying to deal with email validation. When I test my app, I fill the Email TextInput with a valid string, something like Hello#email.com, however, the nonValidInput bool stays at null, and subsequent attempts to post the Email adress don't work either, the nonValidInput bool now it's true when it must be false when entering a correct email adress.
The _onSubmit script is called when the button is pressed.
Here's my code:
state = { username: null, password: null, nonValidInput: null }
_validar = () => {
let email = this.state.username
let pattern = /^(([^<>()\[\]\\.,;:\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,}))$/
if(pattern.test(String(email).toLowerCase) == true) {
this.setState({ nonValidInput: false })
} else {
this.setState({ nonValidInput: true })
}
console.warn(this.state.nonValidInput)
}
_onSubmit = () =>{
this._validar()
if(this.state.nonValidInput == false) {
const { username, password } = this.state;
} else {
this.setState({ nonValidInput: true })
}
}
Again thank you for your answers.
I found a couple of mistakes in your code.
this.setState is an async process. So call your console.warn() as a callback function.
if (pattern.test(String(this.state.username).toLowerCase()) == true) {
this.setState({ nonValidInput: false }, () => console.warn("true"));
} else {
this.setState({ nonValidInput: true }, () => console.warn("false"));
}
and make _onSubmit function as async until it process _validar function.
_onSubmit = async () => {
await this._validar();
if (this.state.nonValidInput == false) {
const { username, password } = this.state;
} else {
this.setState({ nonValidInput: true });
}
};
toLowerCase is a method, you can't call it as,
pattern.test(String(email).toLowerCase)
Change it to
pattern.test(String(email).toLowerCase())
Finally i see you are duplicating your code. In order to make your code clean add your validation part inside submit.
_onSubmit = () => {
let pattern = /^(([^<>()\[\]\\.,;:\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,}))$/;
if (pattern.test(String(this.state.username).toLowerCase()) == true) {
this.setState({ nonValidInput: false });
// you can call submit
} else {
this.setState({ nonValidInput: true });
// you can handle error
}
};
Hope this helps you. Feel free for doubts.
Related
So I want to make a login feature, in here server will validate first if the username or password is correct or not.
I'm using store, react - redux.
Here is my code when login button pressed
const [statusLogin,setStatusLogin] = useState(null)
let loginInfo = []
function loginButton(){
(async () => {
loginInfo = {username:username,password:password}
const { status } = await dispatch(getUser(loginInfo))
if (status==1){
console.log(status,'in status if 1')
setStatusLogin('granted')
}else{
console.log(status,'in status if else')
setStatusLogin(null)
}
})();
}
Here is my store that suppose to return value 1 or else
if it returned value 1 geb statusLogin will changed as granted
export function getUser(body){
return dispatch =>{
if (!body){
setTimeout(() => {
console.log('no username/pass')
}, 2000);
}else{
setTimeout(() => {
console.log('username/pass validated returning with value 1')
}, 2000);
}
}
}
help me please
This might help
...
function loginButton() {
(async () => {
loginInfo = { username: username, password: password };
await dispatch(getUser(loginInfo, callback));
})();
}
function callback = (status) => {
if (status == 1) {
console.log(status, "in status if 1");
setStatusLogin("granted");
} else {
console.log(status, "in status if else");
setStatusLogin(null);
}
};
reducer.js
export function getUser(body, callback){
return dispatch =>{
if (!body){
setTimeout(() => {
console.log('no username/pass');
callback(0);
}, 2000);
}else{
setTimeout(() => {
console.log('username/pass validated returning with value 1')
callback(1);
}, 2000);
}
}
}
you can use like:
usEffect(( )=>{
if(statusLogin) getUser()
},[statusLogin])
Another thing, your function should not passed callback in. Instead of using callback to change the state, you can use dispatch to modify the reducer.
Hello im currentenly stuck and im not quite sure whats wrong
my postman login is all fine but my backend dont accept anything so im pretty sure there is something wrong with my method
export default {
data() {
return {
loading: false,
error: null,
login: {
email: "",
password: "",
}
}
},
methods: {
UserLogin: function() {
this.loading = true;
this.axios.post('http://localhost:3000/login', {user: this.login})
.then((res) =>{
this.$cookies.set('jwt', res.data.jwt);
this.$cookies.set('isAdmin', res.data.isAdmin);
this.$router.push('/dashboard');
}).catch(err => {
//fejl
this.error = err.response.data.message;
});
this.loading = false;
},
CheckForNullInObject: function(obj) {
for (let key in obj) {
if(obj[key] == null || obj[key] == "") return false;
}
return true;
}
}
and my backend
router.post('/', async (req, res) => {
if(!req.body.email || !req.body.password) {
res.status(400).json({
message: "missing values1"
});
return
}
always hits the missing values1 no matter what I write
You've POSTed the login data under user, but your backend code doesn't read that property.
Either update your frontend to send the data directly (without user):
this.axios.post('http://localhost:3000/login', { ...this.login })
Or update the backend to read the data from user:
if(!req.body.user.email || !req.body.user.password)
I'm trying to only show the disclosure screen the first time the user logs in by using AsyncStorage. Currently getData is returning a Promise and it goes straight to the landing screen on first login.
Could I get some help to get this functioning the way I want it to?
This is my login handler:
const key = 'key';
const storeData = async () => {
try {
await AsyncStorage.setItem('key', 'true');
} catch (error) {
// saving failed
console.log(error.message);
}
};
const getData = async key => {
let value = '';
try {
value = await AsyncStorage.getItem(key);
return JSON.parse(value);
} catch (e) {
console.log(error.message);
}
};
const _loginHandler = () => {
if (userName == '' || password == '') {
console.log('gagagagagagagagagagagagagagagagag');
} else {
setShowLoading(true);
const payload = {userName: userName.trim(), password: password.trim()};
setUserName('');
setPassword('');
_UserLoginHandler(payload).then(data => {
setShowLoading(false);
if (data.error) {
GlobalShowSnackBar(data.error);
} else {
setTimeout(() => {
setUserId(data);
//props.navigation.replace(getData("key")?'Landing':'Disclosure')
console.log('Key Value ' + JSON.stringify(getData('key'))); <-- this outputs Key Value {"_U":0,"_V":0,"_W":null,"_X":null}
if (getData('key')) {
props.navigation.navigate('Landing');
} else {
storeData(key);
props.navigation.navigate('Disclosure');
}
}, 500);
}
});
}
};
I got it to work with
getData('key').then(val => {
if (val) {
props.navigation.navigate('Landing');
} else {
storeData(key);
props.navigation.navigate('Disclosure');
}
});
Here is my code and I use asyncstorage to set user's name. I get this error
I get a warning saying Can't perform a React state update on an unmounted component. it indicates a memory leak. cancel and asynchronous tasks in the componentWillUnmount method.
UNSAFE_componentWillMount(){
this.getName()
this.disableSEND()
}
getName = async () => {
let value = 'userName'
try {
await AsyncStorage.setItem('NAME', value))
} catch (e) {
Alert.alert(e.message)
}
}
disableSEND = async () => {
let value = await AsyncStorage.getItem('SENDDISABLED')
this.setState({ switch: value == 'true' ? true : false })
let disableBtn = AsyncStorage.getItem('DISABLEBTN')
this.setState({ disableBtn: disableBtn == 'false' ? false : true })
}
disableMSG = async (value) => {
try {
AsyncStorage.setItem('DISABLEMSG', value.toString())
} catch (e) {
Alert.alert(e.message)
}
}
disableBtn = async (disableBtn) => {
try {
AsyncStorage.setItem('DISABLEBTN', disableBtn.toString())
} catch (e) {
Alert.alert(e.message)
}
}
render() {
return (
<DrawerContentScrollView {...this.props}>
</DrawerContentScrollView>
);
}
}
})
I am currently attempting to show a full log of how many times a user has logged in using AsyncStorage.
This is because I want to show a pop-up modal when the user logs in for the first time.
Is there a way to achieve this?
Previously, I have been able to show the user details in the console.log, which shows the email and password in a string format.
However, I am unsure on were to go to from there. Would a for loop be the appropriate solution, or is there a method that is already achieves this?
LOGIN SCREEN -
_loginUser = async () => {
const { password, email } = this.state;
if(email == '' || password == '') {
alert('Please enter all fields');
}
else {
//save data using AsyncStorage
let loginArray = {
email: email,
password: password
}
//key of the item to set
AsyncStorage.setItem('loginArray',
JSON.stringify(loginArray));
console.log(loginArray);
// const logsInfo = await AsyncStorage.getAllKeys('loginArray');
// console.log(this.setState({ logs: logsInfo }));
this.setState({
loading: true
});
this._signInAsync();
}
}
_signInAsync = async () => {
setTimeout(() => {
this.setState({
loading: false,
});
this.props.navigation.navigate("App");
}, 2000);
};
HOMESCREEN -
fetchAllItems = async () => {
try {
const keys = await AsyncStorage.getAllKeys()
const items = await AsyncStorage.multiGet(keys)
this.setState({ userCredentials: items })
Reactotron.log(this.state.userCredentials);
} catch (error) {
console.log(error, "problemo")
}
}
I think you want to know how many times a user logged in your App?
For that you can keep a counter in AsyncStorage.
In LOGIN SCREEN -,
...
// Count of last logged in
let count = 0
try {
const value = await AsyncStorage.getItem("COUNTER");
if (value !== null) {
// We have counter!!
count = parseInt(value) + 1
}
} catch (error) {
// Error retrieving data, ie. count = 0
}
let loginArray = {
email: email,
password: password,
counter: count
};
//key of the item to set
AsyncStorage.setItem("loginArray", JSON.stringify(loginArray));
AsyncStorage.setItem("COUNTER", JSON.stringify(count));
console.log(loginArray);
...
And in HOMESCREEN -,
You will get the total count in AsyncStorage.
...
//Here you will get the cont
const items = await AsyncStorage.getItem("loginArray")
this.setState({ userCredentials: items })
...
items contain 'email', 'password' and 'counter'.