Redirect after form submit React Native - javascript

I have a simple connection form, I want my user to be redirected to my homepage after connection.
action in my form doesn't seem to work as the URL doesn't change after sending the form.
Here is the content of my Login class in my Login.tsx file
constructor(props) {
super(props);
this.state = {
email: "",
password: ""
}
}
handleSubmit() {
const email = this.state.email;
console.log(email);
const password = this.state.password;
console.log(password);
axios.post("http://snapi.epitech.eu/connection", { email, password }
).then(reponse => {
console.log('connect', reponse);
}).catch(error => {
console.log('error', error);
});
}
render() {
//const { dataSource, fromFetch, fromAxios, loading, axiosData } = this.state
return (
<View style={styles.container}>
<Text>Connection</Text>
<form onSubmit={ this.handleSubmit }
action="localhost:19006/home">
<label>email</label>
<TextInput
//name="email"
style={styles.input}
value={ this.state.email }
onChangeText={ email => this.setState({email}) }
//onChange={val => this.onChange('email', val)}
/>
<label>password</label>
<TextInput
style={styles.input}
secureTextEntry={true}
value={ this.state.password }
onChangeText={ password => this.setState({password}) }
//onChange={val => this.onChange('password', val)}
/>
<Button title="Inscription"
type="submit"
onPress={this.handleSubmit.bind(this)}
/>
</form>
</View>
);
}
};

You need to use react native navigation like below:
import { NavigationActions } from 'react-navigation';
const routeName = "Home" // string e.g 'Home'
const params = { // object (key value pair)
key1: value1,
key2: value2
}
NavigationActions.navigate({ routeName, params }),
or
this.props.navigation.navigate(routeName, params)

Related

Firestore doesn't save updated data

export class Register extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
CaloricGoal: 0,
};
this.onSignUp = this.onSignUp.bind(this);
}
onSignUp() {
var {
email,
CaloricGoal,
} = this.state;
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then((result) => {
firebase
.firestore()
.collection("users")
.doc(firebase.auth().currentUser.uid)
.set({
email,
CaloricGoal,
});
console.log(result);
})
.catch((error) => {
console.log(error);
});
}
render() {
var CaloricGoal =
selectedGoal === 1
? (TDEE * details + TDEE).toFixed(0)
: selectedGoal == 2
? (TDEE - caloricDeficit).toFixed(0)
: TDEE.toFixed(0);
return (
<SafeAreaView
style={{ flex: 1, backgroundColor: "white", alignItems: "center" }}
>
<TextInput
style={styles.inputEmail}
label="email"
placeholder="Email Address"
autoCapitalize="none"
autoCompleteType="none"
autoCorrect="false"
keyboardType="email-address"
onChangeText={(email) => this.setState({ email })}
/>
So I'm trying to save email and CaloricGoal in my firestore document, but email is the only one that saves, CaloricGoal will remain 0, I believe it's because after I insert the values of the function and get the result, the state doesn't update itself so It just returns 0, how can I fix that?

handleSubmit with Formik using TypeScript

I have successfully written a Login component in React using plain Javascript. I would now like to convert this component to TypeScript. I have defined some types and also threw in some "any" just to initially compile. Unfortunately, the onClick parameter in my submit button throws the following error:
TS2322: Type '(e?: FormEvent | undefined) => void' is not assignable to type '(event: MouseEvent<HTMLElement, MouseEvent>)
=> void'.
Here is the relevant code:
class Login extends React.Component<LoginProps, LoginState> {
constructor(props) {
super(props);
this.login = this.login.bind(this);
}
async login(values) {
const user = {
email: values.email,
password: values.password,
};
const query = `mutation userLogin(
$user: UserLoginInputs!
) {
userLogin(
user: $user
) {
token
}
}`;
const data: any = await graphQLFetch(query, { user });
if (data && data.userLogin.token) {
const decoded: any = jwt.decode(data.userLogin.token);
const { onUserChange } = this.props;
onUserChange({ loggedIn: true, givenName: decoded.givenName });
const { history } = this.props;
history.push('/');
}
}
render() {
return (
<Formik
onSubmit={this.login}
validationSchema={loginSchema}
initialValues={{
email: '',
password: '',
}}
>
{({
handleSubmit,
handleChange,
values,
}) => (
<Card>
<Card.Body>
<Form>
<Form.Group>
<Form.Label>E-mail</Form.Label>
<Form.Control
name="email"
value={values.email}
onChange={handleChange}
/>
</Form.Group>
<Form.Group>
<Form.Label>Password</Form.Label>
<Form.Control
name="password"
value={values.password}
onChange={handleChange}
/>
</Form.Group>
</Form>
<Button
type="button"
variant="primary"
onClick={handleSubmit}
>
Submit
</Button>
</Card.Body>
</Card>
)}
</Formik>
);
}
}
I'm new to TypeScript and don't fully understand why an error occurs regarding e versus event when the login function does not explicitly reference either of those. Can someone please help me assign types to my handleSubmit function (aka login)?
I hope that example could help you to resolve your issue
import { Field, Form, Formik } from 'formik';
import * as React from 'react';
import './style.css';
interface MyFormValues {
firstName: string;
}
export default function App() {
const initialValues: MyFormValues = { firstName: '' };
const getSubmitHandler =
() =>
(values, formik) => {
console.log({ values, formik });
alert(JSON.stringify(values, null, 2));
formik.setSubmitting(false);
};
return (
<div>
<Formik
initialValues={initialValues}
onSubmit={getSubmitHandler()}
>
{(formik) => (
<Form>
<label htmlFor="firstName">First Name</label>
<Field id="firstName" name="firstName" placeholder="First Name" />
<button
type="button"
onClick={(event) =>
getSubmitHandler()(formik.values, formik)
}
>
Submit
</button>
</Form>
)}
</Formik>
</div>
);
}

React native code is unable to send data to django api

I am a beginner and I'm using Django in the backend of my react native app. I am unable to add data to the django admin panel from my app using fetch method. I am not getting any errors but my data is not getting posted to the backend.I have used the django api as the url in fetch method.
Please let me know if any other code snippet is required to check.
Would appreciate some help here.
export class LoginScreen extends Component {
constructor() {
super();
this.state = {
email: '',
name: '',
};
}
updateValue(text, field) {
if (field == 'email') {
this.setState({
email: text,
});
} else if (field == 'pwd') {
this.setState({
pwd: text,
});
}
}
submit() {
let collection = {};
collection.email = this.state.email;
collection.pwd = this.state.pwd;
console.warn(collection);
let url='http://10.0.0.2:8000/api/mdlApp/'
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(collection),
})
.then((response) => response.json())
.then((collection) => {
console.log('Success:', collection);
})
.catch((error) => {
console.error('Error:', error);
});
}
render() {
return (
<ImageBackground source={require('../images/bg4.png')} style={styles.bg}>
<SafeAreaView style={styles.container}>
<Logo />
<View style={styles.container1}>
<TextInput
style={styles.inputBox}
name="email"
placeholder="Enter Your Email"
placeholderTextColor="#ffffff"
onChangeText={(text) => this.updateValue(text, 'email')}
/>
<TextInput
style={styles.inputBox}
name="pwd"
placeholder="Enter Your Password"
secureTextEntry={true}
placeholderTextColor="#ffffff"
onChangeText={(text) => this.updateValue(text, 'pwd')}
/>
<TouchableOpacity
//onPress={() => this.props.navigation.navigate('HomeApp')}
onPress={() => this.submit()}
style={styles.button}
htmlType="submit">
<Text style={styles.buttonText}> LOGIN </Text>
</TouchableOpacity>
</View>
<View style={styles.signupTextCont}>
<Text style={styles.signupText}>Don't have an account yet?</Text>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('Register')}
style={styles.signupButton}>
<Text>Register Now</Text>
</TouchableOpacity>
</View>
</SafeAreaView>
</ImageBackground>
);
}
}
change ur code as follows..install axios first
submit = () => {
const url='http://10.0.0.2:8000/api/mdlApp/'
let collection = {
email: this.state.email,
pwd: this.state.pwd
};
axios.post(`${url}`, collection, {
headers: {
'content-type': 'application/json'
}
} ).then(res => {
console.log(res.data)
}))
}

How to fire two functions on single button click

Hello stackoverflow community I am having problem in using onpress method. Actually i want to fire two functions on a single button click like if i press Register button the validate() function and userRegister function works first validate function validate all the fields and then register function registers user into db. I seen setState is responsible for this kind of behaviour since i m new in react native development so i cant implement this kind of functionality
my code :
import React, { Component } from 'react';
import {ToastAndroid, StyleSheet, View, TextInput, Button, Text, Alert } from 'react-native';
export default class Project extends Component {
constructor(props) {
super(props)
this.state = {
UserName: '',
UserEmail: '',
UserPassword: '',
cpassword: "",
UserCity: ''
};
}
Validate=()=>{
if(this.state.UserName == ""){
ToastAndroid.show('Enter UserName',ToastAndroid.SHORT)
}
else if(this.state.UserEmail == ""){
ToastAndroid.show('Enter Email',ToastAndroid.SHORT)
}
else if(this.state.UserPassword == ""){
ToastAndroid.show('Enter Password',ToastAndroid.SHORT)
}
else if(this.state.cpassword == ""){
ToastAndroid.show('Enter Confirm Password',ToastAndroid.SHORT)
}
else if (this.state.UserPassword != this.state.cpassword){
ToastAndroid.show('Password did not match',ToastAndroid.SHORT)
}
else if(this.state.UserCity == ""){
ToastAndroid.show('Enter City Name',ToastAndroid.SHORT)
}
else {
ToastAndroid.show('User Registration Sucessfull', ToastAndroid.SHORT)
}
console.log(this.state)
}
UserRegistrationFunction = () =>{
const {UserName} = this.state;
const {UserEmail} = this.state;
const {UserPassword} = this.state;
const {UserCity} = this.state;
fetch('http://192.168.0.107/loginrn/user_registration.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: this.state.UserName,
email: this.state.UserEmail,
password: this.state.UserPassword,
//confpassword: this.state.cpassword
city : this.state.UserCity,
})
}).then((response) => response.json())
.then((responseJson) => {
// Showing response message coming from server after inserting records.
Alert.alert(responseJson);
}).catch((error) => {
console.error(error);
});
}
render() {
return (
<View style={styles.MainContainer}>
<Text style= {styles.title}>User Registration Form</Text>
<TextInput
placeholder="Enter User Name"
onChangeText={name => this.setState({UserName : name})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
/>
<TextInput
placeholder="Enter User Email"
onChangeText={email => this.setState({UserEmail : email})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
/>
<TextInput
placeholder="Enter User Password"
onChangeText={password => this.setState({UserPassword : password})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
//secureTextEntry={true}
/>
<TextInput
placeholder="Enter User Confirm Password"
onChangeText={cpassword => this.setState({cpassword})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
//secureTextEntry={true}
/>
<TextInput
placeholder="Enter User City Name"
onChangeText={city => this.setState({UserCity : city})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
//secureTextEntry={true}
/>
<Button title="Click Here To Register"
onPress={this.Validate}
color="#2196F3" />
<Button title = "Next" onPress={this.UserRegistrationFunction} color = "#2196F3"/>
</View>
);
}
}
Pass the validate function to onPress = {()=> this.validate()}
And then pass the UserRegistrationFunction in validate function at the end.
import React, { Component } from 'react';
import {ToastAndroid, StyleSheet, View, TextInput, Button, Text, Alert } from 'react-native';
export default class Project extends Component {
constructor(props) {
super(props)
this.state = {
UserName: '',
UserEmail: '',
UserPassword: '',
cpassword: "",
UserCity: ''
};
}
Validate=()=>{
if(this.state.UserName == ""){
ToastAndroid.show('Enter UserName',ToastAndroid.SHORT)
}
else if(this.state.UserEmail == ""){
ToastAndroid.show('Enter Email',ToastAndroid.SHORT)
}
else if(this.state.UserPassword == ""){
ToastAndroid.show('Enter Password',ToastAndroid.SHORT)
}
else if(this.state.cpassword == ""){
ToastAndroid.show('Enter Confirm Password',ToastAndroid.SHORT)
}
else if (this.state.UserPassword != this.state.cpassword){
ToastAndroid.show('Password did not match',ToastAndroid.SHORT)
}
else if(this.state.UserCity == ""){
ToastAndroid.show('Enter City Name',ToastAndroid.SHORT)
}
else {
this.UserRegistrationFunction();
}
console.log(this.state)
}
UserRegistrationFunction = () =>{
const {UserName} = this.state;
const {UserEmail} = this.state;
const {UserPassword} = this.state;
const {UserCity} = this.state;
fetch('http://192.168.0.107/loginrn/user_registration.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: this.state.UserName,
email: this.state.UserEmail,
password: this.state.UserPassword,
//confpassword: this.state.cpassword
city : this.state.UserCity,
})
}).then((response) => response.json())
.then((responseJson) => {
// Showing response message coming from server after inserting records.
Alert.alert(responseJson);
}).catch((error) => {
console.error(error);
});
}
render() {
return (
<View style={styles.MainContainer}>
<Text style= {styles.title}>User Registration Form</Text>
<TextInput
placeholder="Enter User Name"
onChangeText={name => this.setState({UserName : name})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
/>
<TextInput
placeholder="Enter User Email"
onChangeText={email => this.setState({UserEmail : email})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
/>
<TextInput
placeholder="Enter User Password"
onChangeText={password => this.setState({UserPassword : password})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
//secureTextEntry={true}
/>
<TextInput
placeholder="Enter User Confirm Password"
onChangeText={cpassword => this.setState({cpassword})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
//secureTextEntry={true}
/>
<TextInput
placeholder="Enter User City Name"
onChangeText={city => this.setState({UserCity : city})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
//secureTextEntry={true}
/>
<Button title="Click Here To Register"
onPress={()=>this.Validate()}
color="#2196F3" />
<Button title = "Next" onPress={this.UserRegistrationFunction} color = "#2196F3"/>
</View>
);
}
}
As i mentioned below, You can call two function like this (in class component)
login=()=>{
console.log('login')
}
register =()=>{
console.log('register')
}
<Button title = "Next" onPress={()=>[this.user(),this.register()]}/>
According to your requirement, You should use something like this.
import React, { Component } from 'react';
import {
Alert,
View,
Text,
Image,
TouchableOpacity,
Button,
TextInput,
} from 'react-native';
class HomeScreen extends Component {
state = {
date: '',
month: '',
year: '',
isErrorDate: false,
isErrorDateLenght: false,
isErrorMonth: false,
isErrorMonthLength: false,
isErrorYear: false,
isErrorYearLength: false,
};
onChangeDate = value => {
this.setState({
date: value,
isErrorDate: false,
isErrorDateLenght: false,
});
};
onChangeMonth = value => {
this.setState({
month: value,
isErrorMonth: false,
isErrorMonthLength: false,
});
};
onChangeYear = value => {
this.setState({
year: value,
isErrorYear: false,
isErrorYearLength: false,
});
};
doRegister = () => {
console.log('you have registered');
};
checkDate = () => {
//validation part or function
const { date, month, year } = this.state;
let isErrorDate = date.trim() === '' ? true : false;
let isErrorDateLenght =
date.length > 2 || !/^[0-9]+$/.test(date) || date > 31 ? true : false;
let isErrorMonth = month.trim() === '' ? true : false;
let isErrorMonthLength =
month.length > 2 || !/^[0-9]+$/.test(month) || month > 12 ? true : false;
let isErrorYear = year.trim() === '' ? true : false;
let isErrorYearLength =
year.length > 4 || !/^[0-9]+$/.test(year) ? true : false;
if (
isErrorDate ||
isErrorDateLenght ||
isErrorMonth ||
isErrorMonthLength ||
isErrorYear ||
isErrorYearLength
) {
this.setState({
isErrorDate: isErrorDate,
isErrorDateLenght: isErrorDateLenght,
isErrorMonth: isErrorMonth,
isErrorMonthLength: isErrorMonthLength,
isErrorYear: isErrorYear,
isErrorYearLength: isErrorYearLength,
});
Alert.alert('invalid date /month/ year');
} else {
//submit date and call other functions
this.doRegister();
}
};
render() {
return (
<View style={{ flex: 1 }}>
<View>
<View>
<View style={{ padding: 10 }}>
<TextInput
placeholder="DD"
keyboardType="number-pad"
value={this.state.date}
onChangeText={this.onChangeDate}
/>
</View>
<View style={{ padding: 10 }}>
<TextInput
placeholder="MM"
keyboardType="number-pad"
value={this.state.month}
onChangeText={this.onChangeMonth}
/>
</View>
<View style={{ padding: 10 }}>
<TextInput
placeholder="AA"
keyboardType="number-pad"
value={this.state.year}
onChangeText={this.onChangeYear}
/>
</View>
</View>
</View>
<View>
<Button title ="Next" onPress={this.checkDate}/>
</View>
</View>
);
}
}
export default HomeScreen;
Change this according to your requirement. Feel free for doubts

TypeError: undefined is not an object (evaluating 'navigation.navigate')

I have been experimenting on a react-native project. I have a basic login screen with two buttons, one to login and one to take you to the "forgot password" screen. What is troubling me is that the login button works normally, but the forgot password button gives the error written in the title.
Login screen:
import React from 'react';
import { View, StyleSheet } from 'react-native';
import {
Icon, Text, Item, Input, Button
} from 'native-base';
import { firebaseAuth } from '../../environment/config';
export default class Login extends React.Component {
state = {
email: '', password: '', errorMessage: null
};
handleLogin = () => {
const { email } = this.state;
const { password } = this.state;
firebaseAuth
.signInWithEmailAndPassword(email, password)
.then(() => {
const { navigation } = this.props;
navigation.navigate('Authentication');
})
.catch(error => this.setState({ errorMessage: error.message }));
};
forgotPass = () => {
const { navigation } = this.props;
navigation.navigate('ForgotPassword');
};
render() {
const { errorMessage } = this.state;
return (
<View style={styles.container}>
{/* <Text style={styles.heading}>Login</Text> */}
{errorMessage && <Text style={{ color: 'red' }}>{errorMessage}</Text>}
<Item>
<Icon active name="person" />
<Input
autoCapitalize="none"
placeholder="Email"
onChangeText={email => this.setState({ email })}
value={this.email}
/>
</Item>
<Item>
<Icon active name="lock" />
<Input
secureTextEntry
autoCapitalize="none"
placeholder="Password"
onChangeText={password => this.setState({ password })}
value={this.password}
/>
</Item>
<Button
transparent
dark
style={styles.forgotBtn}
onPress={this.forgotPass}
>
<Text>Forgot Password </Text>
</Button>
<Button
style={styles.signupBtn}
rounded
dark
block
onPress={this.handleLogin}
>
<Text>Log In </Text>
</Button>
</View>
);
}
}
and the App.js
const SwitchNavigator = createSwitchNavigator(
{
Loading,
SignUp,
Login,
Main,
Authentication,
LoginRegisterComponent,
ForgotPassword
},
{
initialRouteName: 'Loading',
headerMode: 'none'
}
);
const App = createAppContainer(SwitchNavigator);
export default App;
I have checked other questions that are similar to this one :
undefined is not an object (evaluating 'navigation.navigate')
&&
I am getting undefined is not an object (evaluating 'this.props.navigation.navigate')
The answers given there aren't of much help and I cannot understand why the one button is working and the other one is not.

Categories

Resources