如何使用Redux在React Native中处理延迟API响应?

时间:2019-10-05 21:21:08

标签: api react-native google-cloud-functions

我正在构建一个本机应用程序,当用户尝试登录时,我调用firebase.CreateUser,然后调用firebase函数中的api在我的数据库中创建该用户(Firebase Real-Time)。问题是,当执行componentDidUpdate时,我的firebaseFunction仍然没有结果,然后只有在屏幕上点击时我的道具才会更新。我想知道如何处理。 我正在使用redux。

遵循我的代码:

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Button, Image,Alert} from 'react-native';
import logo from '../../asserts/logo.png'
import { TouchableOpacity, TextInput } from 'react-native-gesture-handler';
import { Divider,Input} from 'react-native-elements';
import axios from 'axios';
import { connect } from 'react-redux';
import { signupUser} from '../../store/actions/Section/actions';


class Signin extends Component {

state = {
    fullName:'',
    userName:'',
    email:'',
    password:'',
    confirmPassword:'',
    bornDate:'',
    State:'',
    City:''
};

      handleEmailChange = val => {
        this.setState({ email:val });
    };

    handlePasswordChange = val => {
        this.setState({ password:val });
    };

    handleConfirmPasswordChange = val => {
        this.setState({ confirmPassword:val });
    };

    handleNameChange = val => {
        this.setState({ fullName:val });
    };

    handleUserNameChange = val => {
        this.setState({ userName:val });
    };

    handleStateChange = val => {
        this.setState({ State:val });
    };

    handleCityChange = val => {
        this.setState({ City:val });
    };
    handleBornDateChange = val => {
        this.setState({ bornDate:val });
    };



    onSignInUser = () => {

        const {email,password} = this.state
        if(email=='' || password=='')
            return;

        this.props.signUp(this.state.fullName,this.state.userName, this.state.email,this.state.password,this.state.confirmPassword,this.state.bornDate,this.state.State,this.state.City);   
       // this.props.navigation.navigate('User');
  };

  componentDidUpdate() {
    const { idUser, loading,error } = this.props;
    console.log(idUser);
    console.log('aqui');
    if (!loading && error) Alert.alert('Erro', error);
    if (!loading && idUser) this.props.navigation.navigate('User');
  }

render() {
  return (
    <View style={styles.container}>
        <View style={styles.flexCenter}>
            <Image source={logo} style={styles.logoImage}/>
            <Text style={styles.logoText} >HomeShare</Text>
            <Text style={styles.sublogoText} >SignUp</Text>
        </View>
        <Divider style={styles.divider} />
        <View style={styles.flexButton}>
            <View style={styles.inputContainer}>
                <Input style={styles.textInput} onChangeText={this.handleNameChange} value={this.state.fullName} placeholder='Nome'/>
                <Input style={styles.textInput} onChangeText={this.handleUserNameChange} value={this.state.userName}  placeholder='User'/>
                <Input style={styles.textInput} onChangeText={this.handleBornDateChange} value={this.state.bornDate}  placeholder='Nascimento'/> 
                <Input style={styles.textInput} onChangeText={this.handleStateChange} value={this.state.State}  placeholder='Estado'/> 
                <Input style={styles.textInput } onChangeText={this.handleCityChange} value={this.state.City}  placeholder='Cidade'/> 
                <Input style={styles.textInput} onChangeText={this.handleEmailChange} value={this.state.email} placeholder='E-mail' keyboardType={'email-address'}/>
                <Input style={styles.textInput} onChangeText={this.handlePasswordChange} value={this.state.password}  placeholder='Senha' secureTextEntry={true}/>
                 <Input style={styles.textInput} onChangeText={this.handleConfirmPasswordChange} value={this.state.confirmPassword}  placeholder='Confirme sua Senha' secureTextEntry={true}/>
            </View>
            <TouchableOpacity style={styles.button} activeOpacity={0.5} onPress={this.onSignInUser} >
                <View>
                    <Text style={styles.buttonText}>SignIn</Text>
                </View>
            </TouchableOpacity>
            <Text style={{marginTop:10}}>Ou</Text>
            <TouchableOpacity style={styles.button} activeOpacity={0.5} onPress={this.signInUser}>
                <View>
                    <Text style={styles.buttonText}>Entrar com Facebook</Text>
                </View>
            </TouchableOpacity>
        </View>
    </View>
  );
}


}



const mapStateToProps = ({ section: { restoring, loading, user, error, logged, idUser } }) => ({
    restoring: restoring,
    loading: loading,
    user: user,
    error: error,
    logged: logged,
    idUser: idUser
  });



  const mapDispatchToProps = {
        signUp:signupUser
  };

  export default connect(
    mapStateToProps,
    mapDispatchToProps
  )(Signin); 

我的动作:

    export const signupUser = (fullName,userName, email,password,confirmPassword,bornDate,State,City) => dispatch => { dispatch(sessionLoading());
    firebaseService.auth().createUserWithEmailAndPassword(email, password).then(user => {
    console.log(user);
                   firebaseService.auth().currentUser.getIdToken(true).then(function(idToken) {
  SectionService.signIn(idToken,fullName,userName, email,password,confirmPassword,bornDate,State,City).then((response) =>{
    console.log(response);
    dispatch(sessionSetId(response));

  }).catch(e=> {
    dispatch(sessionError(e));
  });
   }).catch(function(error) {
     dispatch(sessionError(e));
  });

 })
 .catch(error => {
  dispatch(sessionError(error.message));
  });

1 个答案:

答案 0 :(得分:1)

一种建议的解决方案是处理createUser回调中的帐户创建,并使用云函数中的其他数据对其进行更新。另外,您可以设置一个用于查找文档的侦听器,然后将创建该侦听器并通知该侦听器。

我个人在客户端上创建用户文档,因为我使用仅在客户端上可用的一些数据来创建文档,但是您的用例将决定您的首选方法。