Reputation: 61
I am very new to React Native and try to show a popup if an error ist throwen. But I dont get it to work. Thats my code:
import React, { useState, useEffect } from 'react'
import { Alert, Modal, TouchableOpacity, StyleSheet, View, Pressable } from 'react-native'
import { Text } from 'react-native-paper'
import Background from '../components/Background'
import Logo from '../components/Logo'
import Header from '../components/Header'
import Button from '../components/Button'
import TextInput from '../components/TextInput'
import BackButton from '../components/BackButton'
import { theme } from '../core/theme'
import { emailValidator } from '../helpers/emailValidator'
import { passwordValidator } from '../helpers/passwordValidator'
import Icon from 'react-native-vector-icons/FontAwesome5';
export default function LoginScreen({ navigation }) {
const [email, setEmail] = useState({ value: '', error: '' })
const [password, setPassword] = useState({ value: '', error: '' })
const [hidePass, setHidePass] = useState(true);
const onLoginPressed = () => {
const emailError = emailValidator(email.value)
const passwordError = passwordValidator(password.value)
if (emailError || passwordError) {
setEmail({ ...email, error: emailError })
setPassword({ ...password, error: passwordError })
return
}else{
const SignUp = async () => {
try {
const response = await fetch('https://www.ecample.com/endpoint', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: email.value,
password: password.value
})
})
let json = await response.json()
if ((typeof json.token !== 'undefined') && (json.token.length > 230)) {
alert('fdgdg')
} else {
navigation.reset({
index: 0,
routes: [{ name: 'ErrorPage' }],
})
}
} catch (err) {
console.log(err)
return (
<View style={styles.centeredView}>
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
Alert.alert("Modal has been closed.");
setModalVisible(!modalVisible);
}}
>
<View style={styles.centeredView}>
<View style={styles.modalView}>
<Text style={styles.modalText}>Hello World!</Text>
<Pressable
style={[styles.button, styles.buttonClose]}
onPress={() => setModalVisible(!modalVisible)}
>
<Text style={styles.textStyle}>Hide Modal</Text>
</Pressable>
</View>
</View>
</Modal>
<Pressable
style={[styles.button, styles.buttonOpen]}
onPress={() => setModalVisible(true)}
>
<Text style={styles.textStyle}>Show Modal</Text>
</Pressable>
</View>
);
}
}
} // ende else
}
return (
<Background>
<BackButton goBack={navigation.goBack} />
<Logo />
<Header>Bitte geben Sie Ihre Daten ein.</Header>
<TextInput
label="E-Mail"
returnKeyType="next"
value={email.value}
onChangeText={(text) => setEmail({ value: text, error: '' })}
error={!!email.error}
errorText={email.error}
autoCapitalize="none"
autoCompleteType="email"
textContentType="emailAddress"
keyboardType="email-address"
/>
<TextInput
label="Passwort"
returnKeyType="done"
value={password.value}
onChangeText={(text) => setPassword({ value: text, error: '' })}
error={!!password.error}
errorText={password.error}
secureTextEntry={hidePass ? true : false}
/>
<Icon style={styles.eyeContainer}
name={hidePass ? 'eye-slash' : 'eye'}
size={15}
color="grey"
onPress={() => setHidePass(!hidePass)}
/>
<View style={styles.forgotPassword}>
<TouchableOpacity
onPress={() => navigation.navigate('ResetPasswordScreen')}
>
<Text style={styles.forgot}>Passwort vergessen?</Text>
</TouchableOpacity>
</View>
<Button color="#1584a5" mode="contained" onPress={onLoginPressed}>
Login
</Button>
<View style={styles.row}>
<Text>Keinen Account? </Text>
<TouchableOpacity onPress={() => navigation.replace('RegisterScreen')}>
<Text style={styles.link}>Jetzt registrieren</Text>
</TouchableOpacity>
</View>
</Background>
)
}
I tried different modules and scripts but I cant get a popup. The endpoint works fine. I receive a token, an error 403 or an html with 503 as answer. Therefore I used the catch error.
I nearly tried every Modal, Popup, Alert which I could find in the Internet.
Upvotes: 0
Views: 3791
Reputation: 248
const SignUp = async () => {
try {
const response = await fetch('https://www.example.com/endpoint', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: email.value,
password: password.value
})
})
if (response.status === 200) {
let json = await response.json()
if ((typeof json.token !== 'undefined') && (json.token.length > 230)) {
alert('fdgdg')
} else {
navigation.reset({
index: 0,
routes: [{ name: 'ErrorPage' }],
})
}
} else {
throw new Error(`failed due to status code ${response.status}`);
}
} catch (err) {
console.log(err)
// write code to open modal here
//openErrorModal(err)
}
}
Upvotes: 0
Reputation: 6967
You can use Alert component from react-native.
fetchEvents() {
fetch('http://www.wrongurl.com', {
method: 'GET',
redirect: 'follow'
})
.then(function(response) {
if (response.status == 200) {
let responseText = JSON.stringify(response.text());
console.log(responseText);
}
else throw new Error('HTTP response status not code 200 as expected.');
})
.catch(function(error) {
Alert.alert(error); // Using this line
});
}
Upvotes: 1