How do I get this handleSubmit on a Formik form to perform a Post request - react-native

My handleSubmit function on a Formik form is not properly sending a Post request to my backend API. I believe I have the code 97% of the way there, but don't quite understand the nuances of what is missing.
The form has an email field, and I need the Submit to pass that email string to a POST request. The code below has 4 files at play: Enter-Email.js, SessionStore.js, UserService.js and request.js.
I believe most of the problem is in my handleSubmit function in Enter-Email.js and my #action sendResetCode in SessionStore.js.
Thanks for any assistance.
Enter-Email.js:
import React, { Component, Fragment } from "react";
import { observer } from "mobx-react/native";
import { Formik } from "formik";
import * as yup from "yup";
#observer
class EnterEmail extends Component {
handleSubmit = async ({ <----- function I think has the problem
email,
values,
}) => {
const {
navigation: { navigate },
sessionStore: { sendResetCode }
} = this.props;
let response = await sendResetCode({ <------ the function to make the POST request!
email: email
});
if (response) {
return navigate("VerificationCode", { values });
} else {
return Alert(
{ message: "Error sending the reset link" },
"There was an error sending the reset link. Please try again."
);
}
}
render() {
return (
<SafeAreaView style={{ flex: 1 }}>
<Text>Enter your e-mail to receive a link to reset your password</Text>
<Formik
initialValues={{ email: ''}}
onSubmit={this.handleSubmit}
validationSchema={yup.object().shape({
email: yup
.string()
.email()
.required(),
})}
>
{({ values, handleChange, setFieldTouched, handleSubmit }) => (
<Fragment>
<View>
<View>
<TextInputGroup
id="email"
keyboardType="email-address"
label="Email"
onBlur={() => setFieldTouched("email")}
value={values.email}
onChangeText={handleChange("email")}
/>
</View>
</View>
<View>
<LargeButton
text="Send Reset Link"
onPress={handleSubmit}
/>
</View>
</Fragment>
)}
</Formik>
</SafeAreaView>
);
}
}
export default EnterEmail;
SessionStore.js:
#action sendResetCode = async (emailField: Object): Promise<void> => {
let res = await userService.sendResetCode(emailField);
// if it fails, return res.success to trigger error on enter-email.js
if (!res.success) {
return res.success;
}
};
UserService.js:
// to send code to email that was entered:
userService.sendResetCode = async (
body: Object
): Promise<ApiResponse<Nurse>> => {
const response: Response = await request.post(
`/v1/password_resets`, <---- backend endpoint which works
body
);
return handleResponse(response);
};
request.js:
post(url, body, useBody) {
return fetch(this._buildUrl(url), {
method: "POST",
headers: getCommonHeaders(useBody),
body: useBody ? body : JSON.stringify(body)
});
},
In case it matters, here is the versions in Package.json:
"react-native": "https://github.com/expo/react-native/archive/sdk-32.0.0.tar.gz",
"native-base": "^2.12.1",
"react": "16.8.0",
"react-navigation": "^3.11.0",
"formik": "^1.5.8",
"mobx": "5.9.4",
"mobx-react": "5.4.4",

Related

RTK Query Error: 'AbortError: Aborted' while running test

I'm trying to run a test on login form submit which goes through a Rest API call to authenticate a user.
I have configured MSW for mocking the rest API. Whenever I am running the npm test command the rest api call isn't going through and returning an error. Seems like the mock API isn't working in this case
I have configured MSW for mocking the rest API. I am attaching the handler file, jest setup file and screen file below for reference.
jest.setup.config
import mockAsyncStorage from '#react-native-async-storage/async-storage/jest/async-storage-mock';
import 'whatwg-fetch';
global.XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
jest.mock('#react-native-async-storage/async-storage', () => mockAsyncStorage);
login.screen.tsx
import React from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
import { Button, Pressable, SafeAreaView, Text, View } from 'react-native';
import styles from './EmailLogin.style';
import Input from '../../components/Input/Input.component';
import { color } from '../../theme';
import LinearGradient from 'react-native-linear-gradient';
import { setUser } from '../../stores/user.reducer';
import { useLoginUserMutation } from '../../services/api/auth';
import { useAppDispatch } from '../../hooks/redux';
const EMAIL_PATTERN = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}$/i;
interface IEmailFormInputs {
email: string;
password: string;
}
const EmailLogin: React.FC = ({ navigation }: any) => {
const dispatch = useAppDispatch();
const [loginUser, { isLoading, isError, error, isSuccess }] =
useLoginUserMutation();
const onSubmit: SubmitHandler<IEmailFormInputs> = async requestData => {
try {
const { result } = await loginUser(requestData).unwrap();
dispatch(setUser(result));
navigation.navigate('Home');
} catch (err) {
console.log(err);
}
};
const {
control,
handleSubmit,
formState: { errors },
} = useForm<IEmailFormInputs>({
mode: 'onChange',
defaultValues: {
email: '',
password: '',
},
});
return (
<SafeAreaView style={styles.whiteBackground}>
<View style={styles.mainContainer}>
<View style={styles.welcomeTextContainer}>
<Text style={styles.welcomeTextTitle}>HELLO,</Text>
<Text style={styles.welcomeTextSubTitle}>Welcome back</Text>
</View>
<View style={styles.inputContainer}>
<Input
name="email"
control={control}
rules={{
pattern: {
value: EMAIL_PATTERN,
message: 'Invalid email address',
},
}}
error={errors.email}
placeholder={'Email'}
autoCapitalize={'none'}
autoCorrect={false}
/>
</View>
<View style={styles.inputContainer}>
<Input
name="password"
control={control}
rules={{
minLength: {
value: 3,
message: 'Password should be minimum 3 characters long',
},
}}
secureTextEntry={true}
error={errors.password}
placeholder={'Password'}
autoCapitalize={'none'}
autoCorrect={false}
/>
</View>
<Pressable onPress={handleSubmit(onSubmit)}>
<LinearGradient
start={{ x: 0, y: 0 }}
end={{ x: 1, y: 0 }}
colors={color.gradient.primary}
style={styles.buttonContainer}>
<Text style={styles.buttonText}>Login</Text>
</LinearGradient>
</Pressable>
</View>
</SafeAreaView>
);
};
export default EmailLogin;
login.spec.js
import React from 'react';
import { render, screen, fireEvent, waitFor, act } from '../../test-utils';
import { server } from '../../mocks/server';
import EmailLogin from './EmailLogin.screen';
describe('Home', () => {
//handles valid input submission
it('handle valid form submission', async () => {
await render(<EmailLogin />);
await act(async () => {
fireEvent(
screen.getByPlaceholderText('Email'),
'onChangeText',
'sample#email.com',
);
fireEvent(
screen.getByPlaceholderText('Password'),
'onChangeText',
'password',
);
fireEvent.press(screen.getByText('Login'));
//expected result on success login to be mentioned here
});
});
});
mocks/handler.js
import { rest } from 'msw';
import config from '../config';
export const handlers = [
rest.post(`*url*/user/auth`, (req, res, ctx) => {
console.log(req);
// successful response
return res(
ctx.status(200),
ctx.json({
success: true,
result: {
auth_token: ['authtoken'],
email: req.bodyUsed.email,
id: 1,
first_name: 'xxx',
last_name: 'xxx',
number: 'xxxxxxx',
user_state: 1,
phone_verified: true,
},
}),
);
}),
];
I get the following error when
console.log
{ status: 'FETCH_ERROR', error: 'AbortError: Aborted' }
at src/screens/EmailLogin/EmailLogin.screen.tsx:32:15
at Generator.throw (<anonymous>)

react-native login screen - error when login button is pressed with empty login fields

I have a simple login screen that asks for an email and password.
Login Screen
If the "Sign In" button is pressed and both of the fields are blank I get this error: "null is not an object (evaluating'_this.state.Email')"
Error Screen
Here is the code:
import React, {Component} from 'react';
import {View, Button, ScrollView, AsyncStorage, Alert } from 'react-native';
import colors from '../config/colors';
import { TextInput } from '../components/TextInput';
class SignIn extends Component {
signIn = () => {
const {Email} = this.state;
const {Password} = this.state;
fetch('http://192.168.1.3/Restaurant_App/php/sign_in.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application.json',
},
body: JSON.stringify({
email: Email,
password: Password,
})
}).then((response) => response.json())
.then((responseJson) => {
if (responseJson == Email) {
Alert.alert(responseJson);
AsyncStorage.setItem('email', Email);
this.props.navigation.navigate('Search');
} else {
Alert.alert(responseJson);
}
}).catch((error) => {
console.error(error);
});
};
render() {
return (
<View>
<ScrollView style={{ backgroundColor: colors.background }}>
<TextInput
placeholder="Email..."
onChangeText={Email => this.setState({Email})}
/>
<TextInput
placeholder="Password..."
secureTextEntry={true}
onChangeText={Password => this.setState({Password})}
/>
</ScrollView>
<Button
onPress={() => this.signIn()}
title="Sign In"
/>
</View>
);
}
}
export default SignIn;
I would like it to be so that if the "Sign In" button is pressed with empty fields, I won't get this error. Instead, there should be an alert saying "Please fill in all fields." or something like that.
You should do some validation checks before making the fetch request.
You could do something like this
signIn = () => {
const {Email, Password} = this.state;
if(!this.checkDetails(Email, Password) {
// you could show an alert here, but it is not great UX,
// you should show your user where they have gone wrong,
// by making style changes, a red border around the TextInput,
// text explaining what has gone wrong.
return;
}
fetch('http://192.168.1.3/Restaurant_App/php/sign_in.php', {
...
}).then((response) => response.json())
.then((responseJson) => {
...
}).catch((error) => {
console.error(error);
});
};
checkDetails = (Email, Password) => {
// check that it is a valid email address
// this is a regex that I have used in the past to check email addresses.
const emailIsValid = /^(([^<>()\[\]\\.,;:\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,}))$/.test(Email);
// if the password has a minimum length then you should use that rather than 0
this.setState({emailIsValid, passwordIsValid: Password.length > 0});
if (emailIsValid && Password.length > 0) return true;
return false;
}
Using these new state values for the email and password being valid you could set additional styles and error text beside the fields that are wrong or missing.
<TextInput
placeholder="Email..."
onChangeText={Email => this.setState({Email})}
styles={this.state.emailIsValid ? styles.validEmail : styles.invalidEmail}
/>
{!this.state.emailIsValid && <Text>Please input a valid email</Text>}
<TextInput
placeholder="Password..."
secureTextEntry={true}
onChangeText={Password => this.setState({Password})}
styles={this.state.passwordIsValid ? styles.validPassword : styles.invalidPassword}
/>
{!this.state.passwordIsValid && <Text>Please input a valid password</Text>}
Don't for get to set up your styles for the different states.
const styles = StyleSheet.create({
validEmail: {},
validPassword: {},
invalidEmail: {},
invalidPassword: {}
});
You'll probably want to add initial state values for the emailIsValid and passwordIsValid so that they are set to true so that the correct styles are shown. Also you should define initial state for the Email and Password.
Add a constructor to your class
constructor (props) {
super(props);
this.state = {
Email: '',
Password: '',
emailIsValid: true,
passwordIsValid: true
}
}
I hope that this helps.
You can do at the top of your sign in function something like this:
If(this.state.email.length === 0 || this.state.password.length === 0) {
alert(“please complete the fields”);
return;}

react native modal not close after setState false

I have set modal visibility to false but it still showing. I cant figure out what causes this issue. this my code at loading.js.
I'm use this component in main what happen when setState false but its just close after close simolator and restart the device
import React,{Component} from 'react';
import PropTypes from 'prop-types'
import {View, Image, Modal, StyleSheet, Text} from "react-native";
export default class Loader extends Component{
render(){
const {animationType,modalVisible}=this.props;
return(
<Modal
animationType={animationType}
transparent={true}
visible={modalVisible}>
<View style={styles.wrapper}>
<View style={styles.loaderContainer}>
<Image
source={require('../img/loading.gif')}
style={styles.loaderImage}/>
</View>
</View>
</Modal>
)
}
}
Loader.propTypes={
animationType:PropTypes.string.isRequired,
modalVisible:PropTypes.bool.isRequired
}
this main class
export default class ForoshRah extends Component {
constructor() {
super();
I18nManager.forceRTL(true);
this.state = {
image: null,
images: null,
loadingVisible:false,
};
this.onValueChange2=this.onValueChange2.bind(this);
this.OnSubmiteData=this.OnSubmiteData.bind(this);
}
onValueChange2(value: string) {
this.setState({
Field: value,
});
}
async OnSubmiteData(){
this.setState({loadingVisible:true})
let token = await AsyncStorage.getItem('token',token);
let response = await
fetch(url,{
method:'POST',
headers:{
'Content-Type':'application/json',
Authorization:'JWT'+" "+token,
}
,body: JSON.stringify({
title,
})
})
let register = await response.json();
this.setState({userID:register.id})
if(response.status===200){
this.UploadImage()
}
}
async UploadImage() {
let token = await AsyncStorage.getItem('token',token);
let response = await fetch(url,{
method:'POST',
headers:{
Authorization:'JWT'+" "+token,
},body: formData
})
let uimage = await response;
console.log('user',this.state.userID);
if(response.status=200){
handleCloseModal = () => {
console.log(this.state.loadingVisible);
this.setState({ loadingVisible: false})
});
};
this.props.navigation.dispatch({ type: 'Navigation/BACK' })
}else {
setTimeout(() => {
this.setState({ loadingVisible: false })
}, 100)
}
setTimeout(() => {
this.setState({ loadingVisible: false })
}, 100)
}
render() {
return (
<KeyboardAwareScrollView >
<View style={{marginBottom:'10%'}}>
<Button block style={{backgroundColor:'#8e25a0'}} onPress={this.OnSubmiteData.bind(this)}>
</Button>
</View>
<Loader
modalVisible={loadingVisible}
animationType="fade"
/>
</KeyboardAwareScrollView>
);
}
}
onsubmitdata setState true and after response going to 200 Setstate set false in code main
You cannot just call state name as you have did. You should do like below.
<Loader
modalVisible={this.state.loadingVisible}
animationType="fade"
/>

Passing value of component to another Scene to use in post method - react native

I need Some Help as possible.
In my code I have scene that return into my view, an array with names. However, I want to do something also. When I click the name, I want to take the email of the name I have clicked and past to my post method, to return in another scene with information of the email person. Here is my code:
My Users Class with all elements
import React from 'react';
import ListaItens from './ListaUsers'
import BarraNavegacao from './BarraNavegacao';
import {View,Image,Alert,TouchableHighlight,AsyncStorage} from 'react-native';
import axios from 'axios';
export default class Users extends React.Component {
constructor(props) {
super(props);
this.state = {tituloBarraNav: 'Colaboradores',testLocal:''};
}
My refresh function is into Component Users
async refresh() {
let tmp_localData = {};
AsyncStorage.getItem('localData', (err, result) => {
//console.log(result);
tmp_localData = JSON.parse(result);
//console.log('Local temp: ', tmp_localData.User.email);
}).then((result) => {
tmp_localData = JSON.parse(result);
//console.log('Email: ', tmp_localData.email);
axios({
method: 'post',
url: 'my url'
data: {
email: 'someEmail#test.com,
}
},
console.log('aqui esta o email'),
).then((response) => {
//console.log('Get tmpLocal ----------',tmp_localData);
//console.log('Get response ----------',response);
tmp_localData.User = {
"userID": response.data.response.userID,
"displayName": response.data.response.displayName,
"email": response.data.response.email,
"avatar": response.data.response.avatar,
"gender": response.data.response.gender,
"Session": {
"token": response.data.response.token,
},
"FootID": response.data.response.FootID,
};
//this.refresh();
//console.log('Set tmpLocal',tmp_localData);
AsyncStorage.setItem('localData', JSON.stringify(tmp_localData), () => {
}).then((result) => {
this.props.navigator.push({id: 'MenuPrincipal'});
console.log('Navigator',this.props.navigator);
//Alert.alert('Clicou Aqui ');
});
}).catch((error) => {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
Alert.alert('Não foi possivel mudar o utilizador');
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log('erro de ligaçao', error.message);
Alert.alert('Não foi possivel mudar o utilizador');
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('erro de codigo no then', error.message);
Alert.alert('Não foi possivel mudar o utilizador');
}
console.log(error.config);
Alert.alert('Não foi possivel mudar o utilizador');
});
});
}
My render in Users
render(){
const {principal, conteudo,imgConteudo1,imgConteudo2, texto,box}= myStyle;
return(
<View style={principal}>
<BarraNavegacao back navigator={this.props.navigator} tituloProp={this.state.tituloBarraNav}/>
<TouchableHighlight onPress={() => {this.refresh();}}
clearButtonMode={'while-editing'}
activeOpacity={1} underlayColor={'white'}>
<ListaItens/>
</TouchableHighlight>
</View>
);
}
}
I have ListaItems Component that will walk through an array and will put inside ScroolView with map method. So the code is:
My ListaItems Class
import React from 'react';
import { ScrollView} from 'react-native';
import axios from 'axios';
import Items from './Items';
export default class ListaItens extends React.Component {
constructor(props) {
super(props);
this.state = {listaItens: [], listaEmail: [] };
}
componentWillMount() {
//request http
axios.get('my url')
.then((response) => {
this.setState({listaItens: response.data.response})
})
.catch(() => {
console.log('Erro ao imprimir os dados')
});
}
render() {
return (
<ScrollView>
{this.state.listaItens.map(item =>(<Items key={item.email} item={item}/>))}
</ScrollView>
);
}
}
The last component is the component the build what i want to show inside scrollview in ListaItems. The component name is Items. the code is:
My Items Class
import React, {Component} from 'react';
import {Text, Alert, View, Image,} from 'react-native';
export default class Items extends Component {
constructor(props) {
super(props);
this.state = {listaEmail: ''};
}
render() {
const {foto, conteudo, texto, box, test} = estilo;
return (
<View>
<Text/>
<Text/>
<View style={conteudo}>
<Image style={foto} source={{uri: this.props.item.avatar}}/>
<Text style={texto}>{this.props.item.displayName}</Text>
</View>
<View style={test}>
<Text style={texto}>{this.props.item.email}</Text>
</View>
</View>
);
}
}
So, in Users Class for refresh() function in the post method on this email: "someEmail#test.com", I want to be dynamic, when I click the name of a person in Items Class, I want to take the the email here on this.props.item.email and put in parameter on post method of Users Class----refresh()----axios()---Data---email:the email i want to past.
A litle help here, please. I am desperate right now because i have tryied and I did not make it
First move the Touchable to the item
export default class Items extends Component {
render() {
const { foto, conteudo, texto, box, test } = estilo;
return (
<View> //I'm not sure if the this.props.item.email is the one you use, just change it if you need.
<TouchableHighlight onPress={() => { this.props.callback(this.props.item.email); }}
clearButtonMode={'while-editing'}
activeOpacity={1} underlayColor={'white'}>
<Text />
<Text />
<View style={conteudo}>
<Image style={foto} source={{ uri: this.props.item.avatar }} />
<Text style={texto}>{this.props.item.displayName}</Text>
<View style={test}>
<Text>{this.props.item.email}</Text>
</View>
</View>
</TouchableHighlight>
</View>
);
}
}
Them change you function to receive the email param.
refresh = (email) => {
let tmp_localData = {};
AsyncStorage.getItem('localData', (err, result) => {
tmp_localData = result;
}).then((result) => {
axios({
method: 'post',
url: 'my Url',
data: {
email: email,
}
})
})
}
And them you can pass the function to component via props
render() {
const { principal, conteudo, imgConteudo1, imgConteudo2, texto, box } =
myStyle;
return (
<View style={principal} >
<BarraNavegacao back navigator={this.props.navigator} tituloProp={this.state.tituloBarraNav} />
<ListaItens callback={this.refresh} />
</View>
);
}

Why isn't mailchimp API working with fetch?

I'm trying to add an email address to a mailchimp list I have.
This is for a react native app and I'm trying to implement the request using fetch.
This is my code within the component:
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { connect } from 'react-redux';
import { emailChanged, nameChanged, addToWaitingList } from '../actions';
import { Card, CardSection, Input, Button, Spinner } from '../components/Auth';
class addToWaitingListForm extends Component {
onEmailChange(text) {
this.props.emailChanged(text);
}
onButtonPress() {
const { email } = this.props;
this.props.addToWaitingList({ email });
}
renderButton() {
if (this.props.loading) {
return <Spinner size="large" />;
}
return (
<Button onPress={this.onButtonPress.bind(this)}>
Keep me in the loop!
</Button>
);
}
render() {
return (
<View>
<Card>
<CardSection>
<Input
placeholder="your name"
onChangeText={this.onNameChange.bind(this)}
value={this.props.name}
/>
</CardSection>
<CardSection>
<Input
placeholder="email#uni.ac.uk"
onChangeText={this.onEmailChange.bind(this)}
value={this.props.email}
/>
</CardSection>
<Text style={styles.errorTextStyle}>
{this.props.error}
</Text>
<CardSection style={{ borderBottomWidth: 0 }}>
{this.renderButton()}
</CardSection>
</Card>
</View>
);
}
}
const mapStateToProps = ({ auth }) => {
const { email, name, error, loading } = auth;
return { email, name, error, loading };
};
export default connect(mapStateToProps, {
emailChanged,
addToWaitingList
})(addToWaitingListForm);
Add this is my action code for interacting with the mailchimp api:
import Router from '../../navigation/Router';
import { getNavigationContext } from '../../navigation/NavigationContext';
export const addToWaitingList = ({ email }) => {
const emailListID = 'e100c8fe03';
fetch(`https://us13.api.mailchimp.com/3.0/lists/${emailListID}/members/`, {
method: 'POST',
body: JSON.stringify({
'email_address': email,
'status': 'subscribed',
'merge_fields': {
'FNAME': 'Urist',
'LNAME': 'McVankab'
}
})
})
.then(() => addSubscriberSuccess())
.catch(error => console.log(error));
};
const addSubscriberSuccess = () => {
getNavigationContext().getNavigator('root').immediatelyResetStack([Router.getRoute('auth')]);
};
Right now, the error I'm just getting back is ExceptionsManager.js:62 Cannot read property 'type' of undefined and Error: unsupported BodyInit type
What does this mean and how can I fix this?
You need to do two things.
First off you need to send the basic authentication via fetch so you cant do "user:pass" You have to convert it with btoa('user:pass').
Then you have to send it with mode: 'no-cors'
let authenticationString = btoa('randomstring:ap-keyxxxxxxx-us9');
authenticationString = "Basic " + authenticationString;
fetch('https://us9.api.mailchimp.com/3.0/lists/111111/members', {
mode: 'no-cors',
method: 'POST',
headers: {
'authorization': authenticationString,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email_address: "dude#gmail.com",
status: "subscribed",
})
}).then(function(e){
console.log("fetch finished")
}).catch(function(e){
console.log("fetch error");
})