I have been getting loop on my error page when i click retry

153 views Asked by At

When a new User register for the first time, and get an error during submition, This workas expected but after the user tap retry it just loop to error page (RegistrationFailure.js) but behind the scene there is an activity going on.

I need help with this, cause for days i cannot really tell where the problem is.

Register.js

'use strict';

import React, { Component } from 'react';
import { View, StyleSheet, Image, TouchableHighlight, Alert } from 'react-native';
import { Container, Content, Input, Button, Footer, FooterTab, Text } from 'native-base';
import { connect } from 'react-redux';
import StepIndicator from 'react-native-step-indicator';
// import { RegisterFinal, RegisterStepOne, RegisterStepTwo, Progress, Congratulation } from '../components/register'
import RegisterStepOne from '../components/register/RegisterStepOne' 
import RegisterStepTwo from '../components/register/RegisterStepTwo' 
import RegisterFinal from '../components/register/RegisterFinal' 
import ProgressIn from '../components/register/ProgressIn' 
import Congratulation from '../components/register/Congratulation'
import RegistrationFailure from '../components/register/RegistrationFailure'
import { StackActions } from 'react-navigation';
import { register, updateDraft } from '../actions/auth';
import {StepOne} from '../screens/WalkThrough';

import Frisbee from 'frisbee';

import Spinner from 'react-native-loading-spinner-overlay';

//Temprorary api call for confirm pin
const api = new Frisbee({
    baseURI: 'https://localhost:5678', //'http://localhost:3000',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    }
});

const MAX_LENGTH_CODE = 6;
const MAX_LENGTH_NUMBER = 14;

const customStyles = {
    stepIndicatorSize: 30,
    currentStepIndicatorSize: 40,
    separatorStrokeWidth: 2,
    currentStepStrokeWidth: 3,
    stepStrokeCurrentColor: '#222',
    stepStrokeWidth: 1,
    stepStrokeFinishedColor: '#222',
    stepStrokeUnFinishedColor: '#aaaaaa',
    separatorFinishedColor: '#0d6851',
    separatorUnFinishedColor: '#aaaaaa',
    stepIndicatorFinishedColor: '#0d6851',
    stepIndicatorUnFinishedColor: '#ffffff',
    stepIndicatorCurrentColor: '#ffffff',
    stepIndicatorLabelFontSize: 13,
    currentStepIndicatorLabelFontSize: 13,
    stepIndicatorLabelCurrentColor: '#222',
    stepIndicatorLabelFinishedColor: '#ffffff',
    stepIndicatorLabelUnFinishedColor: '#aaaaaa',
    labelColor: '#999999',
    labelSize: 13,
    currentStepLabelColor: '#222'
}

class Register extends Component {
    constructor(props) {
        super(props);
        this.state = {
            onChangeText: false,
            registrationState: 0,
            currentPage: 0,
            confirmationPin: "",
            error: null,

            enterCode: false,
            spinner: false,
        };
    }
    
    //Getting the otp from the api temporary
    _getCode = () => {

        this.setState({ spinner: true });
    
        setTimeout(async () => {
    
          try {
    
            const res = await api.post('/socket.io/1/websocket/', {
              body: {
                ...this.refs.form.getValues(),
                ...this.state.country
              }
            });
    
            if (res.err) throw res.err;
    
            this.setState({
              spinner: false,
              enterCode: true,
              verification: res.body
            });
            this.refs.form.refs.Input.setNativeProps({ text: '' });
    
            setTimeout(() => {
              Alert.alert('Sent!', "We've sent you a verification code", [{
                text: 'OK',
                onPress: () => this.refs.form.refs.Input.focus()
              }]);
            }, 100);
    
          } catch (err) {
            // <https://github.com/niftylettuce/react-native-loading-spinner-overlay/issues/30#issuecomment-276845098>
            this.setState({ spinner: false });
            setTimeout(() => {
              Alert.alert('Oops!', err.message);
            }, 100);
          }
    
        }, 100);
    
    }

    _verifyCode = () => {

        this.setState({ spinner: true });
    
        setTimeout(async () => {
    
          try {
    
            const res = await api.put('/socket.io/1/websocket/', {
              body: {
                ...this.refs.form.getValues(),
                ...this.state.country
              }
            });
    
            if (res.err) throw res.err;
    
            this.refs.form.refs.Input.blur();
            // <https://github.com/niftylettuce/react-native-loading-spinner-overlay/issues/30#issuecomment-276845098>
            this.setState({ spinner: false });
            setTimeout(() => {
              Alert.alert('Success!', 'You have successfully verified your phone number');
            }, 100);
    
          } catch (err) {
            // <https://github.com/niftylettuce/react-native-loading-spinner-overlay/issues/30#issuecomment-276845098>
            this.setState({ spinner: false });
            setTimeout(() => {
              Alert.alert('Oops!', err.message);
            }, 100);
          }
    
        }, 100);
    
    }
    
    onChangeText = (val) => {
        if (!this.state.enterCode) return;
        if (val.length === MAX_LENGTH_CODE)
        this._verifyCode();
    }

    _tryAgain = () => {
        this.refs.form.refs.Input.setNativeProps({ text: '' })
        this.refs.form.refs.Input.focus();
        this.setState({ enterCode: false });
    }

    sendRegistration(){
        let payload = Object.assign({}, {confirmationPin: this.state.confirmationPin}, this.props.registrationDraft)
        console.log({Req: payload});
        this.props.register(payload);
        //This is what i added for the code verification 
        this.state.enterCode ? this._verifyCode() : this._getCode();
    }

    render() {
        return (
            <Container>
                <View style={{ justifyContent: 'center', alignItems: 'center' }}>
                    <Image style={styles.logotop} source={require("../assets/img/proximity.png")} />
                    <Text style={{ fontSize: 30, fontFamily: 'Raleway-Regular', }}>Provisioning</Text>
                </View>
                <View style={styles.stepIndicator}>
                    <StepIndicator
                        customStyles={customStyles}
                        stepCount={4}
                        currentPosition={this.state.currentPage}
                        labels={[]}
                    /> 
                </View>

                <Content>
                    {/* <ErrorBar /> */}
                    {this.state.currentPage === 0 && <RegisterStepOne updateField={(e)=> this.props.updateDraft(e)} params={this.props.registrationDraft} dispatch={this.props.navigation.dispatch} />}
                    {this.state.currentPage === 1 && <RegisterStepTwo  updateField={(e)=> this.props.updateDraft(e)} params={this.props.registrationDraft} />}
                    {this.state.currentPage === 2 && <RegisterFinal updateField={(e)=>this.setState(e)} params={this.state} />}
                    {this.state.currentPage === 3 && this.props.registrationState < 4 && <ProgressIn registrationState={this.props.registrationState} />}
                    {this.state.currentPage === 3 && this.props.registrationState === 4 && <Congratulation styles={styles} navigate={(e) => this.props.navigation.navigate(e)} />}
                    {this.state.currentPage === 3 && this.props.registrationState < 4 && this.props.registerFailed !== true && <RegistrationFailure styles={styles} dispatch={this.props.navigation.dispatch}/>}
                </Content>

                <Spinner
                    visible={this.state.spinner}
                    textContent={'One moment...'}
                    textStyle={{ color: '#222' }}
                />

                {this.state.currentPage < 3 &&
                <Footer style={{ flexDirection: 'row', backgroundColor: 'transparent', height: 70, shadowOffset: { height: 0, width: 0 }, shadowOpacity: 0, elevation: 0 }} transparent noShadow>
                    <FooterTab style={{ margin: 5, backgroundColor: 'transparent', }}>
                        <TouchableHighlight style={styles.submitQuit} onPress={() => {
                            if(this.state.currentPage === 0){
                                this.props.navigation.dispatch(/*StackActions.popToTop()*/StackActions.pop({n: 2}));
                            }else{
                                this.setState({ currentPage: this.state.currentPage - 1 })
                            }
                        }}>
                            <Text style={styles.submitTextQuit}> { this.state.currentPage === 0 ? 'Back' : 'Back' }</Text>
                        </TouchableHighlight>
                    </FooterTab>
                    <FooterTab style={{ margin: 5, backgroundColor: 'transparent', }}>
                        <TouchableHighlight style={styles.submit} onPress={() => {
                            console.log({ isWorking: this.props.isWorking});
                            if (this.props.isWorking){
                                console.log('response for this');
                                return;
                            }
                            console.log(this.state.currentPage)
                            if(this.state.currentPage === 0){
                                if(!this.props.registrationDraft.firstName.length || 
                                    !this.props.registrationDraft.surname.length ||
                                    !this.props.registrationDraft.NINLastSix.length ||
                                    !this.props.registrationDraft.yearOfBirth.length ||
                                    !this.props.registrationDraft.phone.length){
                                        Alert.alert(
                                            'Warning!!!!',
                                            'Fill out the required fields',
                                            [ 
                                              {text: 'OK', onPress: () => console.log('OK Pressed')},
                                            ],
                                            { cancelable: false }
                                          )
                                        console.log("cant go to next page 2")
                                        return;
                                    }
                            }
                            if(this.state.currentPage === 1){
                                if(!this.props.registrationDraft.password.length ||
                                    !this.props.registrationDraft.confirmPassword.length){
                                        Alert.alert(
                                            'Warning!!!!',
                                            'Fill out your Password',
                                            [ 
                                              {text: 'OK', onPress: () => console.log('OK Pressed')},
                                            ],
                                            { cancelable: false }
                                          )
                                        console.log("cant go to next page 3")
                                        return;
                                }
                                if(this.props.registrationDraft.password !== 
                                        this.props.registrationDraft.confirmPassword){
                                            Alert.alert(
                                                'Warning!!!!!!',
                                                'Password do not match',
                                                [ 
                                                  {text: 'OK', onPress: () => console.log('OK Pressed')},
                                                ],
                                                { cancelable: false }
                                              )
                                    console.log("passwords do not match");
                                    return;
                                }
                            }
                            if(this.state.currentPage + 1 === 3){
                                // if(!this.props.registrationDraft.comfirmPin.length)
                                this.sendRegistration();
                            }
                            this.setState({ currentPage: this.state.currentPage + 1 })
                            }}>
                            <Text style={styles.submitText}>{ this.state.currentPage === 2 ? 'Send' : 'Next' }</Text>
                        </TouchableHighlight>
            
                    </FooterTab>
                </Footer>
                }
            </Container>
        )
    }
}

function mapStateToProps(store) {
    return {
        isWorking: store.isWorking,
        // errorMessage: store.auth.regError,
        registered: store.auth.registered,
        registerFailed: store.auth.registerFailed,
        registerFailedMessage: store.auth.registerFailedMessage,
        registrationState: store.auth.registrationState,
        registrationDraft: store.auth.registrationDraft
        // authToken: store.auth.authToken
    };
}
function mapDispatchToProps(dispatch) {
    return {
        register: (user) => dispatch(register(user)),
        updateDraft: (keyValue) => dispatch(updateDraft(keyValue)),
    };
}
export default connect(mapStateToProps, mapDispatchToProps)(Register);

//Registeration styling
const styles = StyleSheet.create({
    container: {
        alignItems: 'center',
        justifyContent: 'center',
    },

    paragraph: {
        margin: 10,
        marginTop: 0,
        fontSize: 20,
        fontWeight: '200',
        textAlign: 'left',
        color: '#090a08',
        fontFamily: 'sans-serif-light',
    },

    logotop: {
        backgroundColor: "transparent",
        marginTop: 25,
        height: 80,
        width: 200,
        resizeMode: 'contain'
    },
    stepIndicator: {
        marginVertical: 10,
        marginTop: 10,
    },
    circles: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: 20,
        alignSelf: 'center',
        color: '#222'
    },
    rowItem: {
        flex: 3,
        paddingVertical: 20
    },
    title: {
        flex: 1,
        fontSize: 20,
        color: '#333333',
        paddingVertical: 16,
        fontWeight: '600'
    },
    body: {
        flex: 1,
        fontSize: 15,
        color: '#606060',
        lineHeight: 24,
        marginRight: 8
    },

    submit:{
        marginTop: 0,
        paddingTop: 4,
        paddingBottom:15,
        marginLeft:40,
        marginRight:40,
        width: 100,
        height: 40,
        backgroundColor:'#2B2B26',
        borderRadius:10,
        borderWidth: 1,
        borderColor: '#fff'
      },

    submitText: {
        color: '#fff',
        textAlign: 'center',
        fontSize: 20,
    },
    submitQuit:{
        marginTop: 0,
        paddingTop: 4,
        paddingBottom:15,
        marginLeft:40,
        marginRight:40,
        width: 100,
        height: 40,
        backgroundColor:'#2B2B26',
        borderRadius:10,
        borderWidth: 1,
        borderColor: '#fff'
      },
    submitTextQuit: {
        color: '#fff',
        textAlign: 'center',
        marginRight: 6,
        fontSize: 20,
    },

    input: {
        backgroundColor: '#ffffff',
        borderBottomWidth: 0,
        marginBottom: 10,
        borderRadius: 2,
        paddingVertical: 5,
        width: '100%'
    },
    placeholder: {
        fontSize: 12
    },
    errorMessage: {
        marginTop: 40
    },
    loggedInDesc: {
        marginTop: 40
    },
    congratulations: {
        fontSize: 30,
        textAlign: 'center',
        color: '#0d6851',
        marginTop: 40,
        fontFamily: 'AvenirLTStd-Roman',
    },
    registrationFailed: {
        fontSize: 30,
        textAlign: 'center',
        color: 'red',
        marginTop: 40,
        fontFamily: 'AvenirLTStd-Roman',
    }

});

RegistrationFailure.js

'use strict';

import React, { Component } from 'react';
import { View, StyleSheet, TouchableHighlight, BackHandler, Alert } from 'react-native';
import { Text, Footer, FooterTab, Container,  } from 'native-base';
import { StackActions, createStackNavigator, createAppContainer  } from 'react-navigation';

const pushAction = StackActions.push({
    routeName: 'Register',
    params: {
      myUserId: 9,
    },
  });

export default class RegisterFinal extends Component {
    
    render() {
        let dispatch = this.props.dispatch;
        // const { goBack } = this.props.navigation;
        return (
            <View style={styles.container}>
                <View>
                    <View>   
                        <View>
                            <Text style={{margin: 4, marginTop: 30,  alignSelf: 'center', color: 'red', fontSize: 20}}>Ooops!!</Text>
                            <Text style={{ margin: 4, marginTop: 20, fontFamily: 'Raleway-Regular', fontSize: 20, textAlign: 'center', color: '#595959', }}>
                                Your submission returned an error</Text>
                            <Text style={{ margin: 4, fontFamily: 'Raleway-Regular', fontSize: 20, textAlign: 'center', color: '#595959', }}> Please go back and try again.
                            </Text>
                        </View>
                        
                        {/* <Footer style={{ backgroundColor: 'transparent', height: 140, shadowOffset: {height: 0, width: 0}, shadowOpacity: 0, elevation: 0}}transparent noShadow>
                            <FooterTab style={{ margin: 10, backgroundColor: 'transparent', justifyContent: 'center' }}>
                                <TouchableHighlight style={styles.submit} onPress={() => { console.log("Proceeding to Start All Over"); dispatch(StackActions.pop({ n: 2 })) }}>
                                    <Text style={styles.submitText}>Retry</Text>
                                </TouchableHighlight>
                            </FooterTab>
                        </Footer> */}
                        <Footer style={{ justifyContent: 'center', marginTop: 140, alignSelf: 'center', flexDirection: 'row', backgroundColor: 'transparent', height: 70, shadowOffset: {height: 0, width: 0}, shadowOpacity: 0, elevation: 0}}transparent noShadow>
                            <FooterTab style={{marginLeft: -10, margin: 5, backgroundColor: 'transparent',}}>
                                <TouchableHighlight style={styles.submit} onPress={() => {
                                        // Alert.alert(
                                        // 'Exit App',
                                        // 'Do you want to exit?',
                                        // [
                                        //     {text: 'No', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
                                        //     {text: 'Yes', onPress: () => {this.props.dispatch(StackActions.pop({n: 1}));
                                    
                                        //     BackHandler.exitApp();}},
                                        // ],
                                        // { cancelable: false });
                                        // return true;
                                    console.log('you just tap quit');
                                    console.log(this.props);
                                    // return this.state.handleBackPress;
                                    this.props.dispatch(StackActions.pop({n: 4}));
                                    
                                    BackHandler.exitApp();
                                }}>
                                    <Text style={styles.submitText}>Quit</Text>
                                </TouchableHighlight>
                            </FooterTab>
                            <FooterTab style={{margin: 5, backgroundColor: 'transparent',}}>
                                <TouchableHighlight style={styles.submit} 
                                    onPress={() => { console.log("Proceeding to Start All Over");
                                    this.props.dispatch(pushAction);
                                }}>
                                    <Text style={styles.submitText}>Retry</Text>
                                </TouchableHighlight>
                            </FooterTab>
                        </Footer>
                       
                    </View>
                </View>
            </View>
        )
    }
}
    
const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'white',
    },
    submit:{
        marginTop: 0,
        paddingTop: 5,
        paddingBottom:15,
        marginLeft:40,
        marginRight:40,
        width: 100,
        height: 40,
        backgroundColor:'#2B2B26',
        borderRadius:10,
        borderWidth: 1,
        borderColor: '#fff'
      },

    submitText: {
        color: '#fff',
        textAlign: 'center',
        fontSize: 20,
    },
});

0

There are 0 answers