получение данных из API и отображение их в плоском списке - PullRequest
0 голосов
/ 11 мая 2019

У меня есть два экрана: MyAddress.js и CreateAddress.js. Когда пользователь входит в систему и переходит на страницу MyAddress в жизненном цикле componentDidMount, я получаю данные из API, который представляет собой список адресов, созданных ранее пользователем. в createAddress пользователь может создать свой новый адрес и снова после его отправки отправляется запрос API и создает новый адрес. Код успешного ответа от API - 1. проблема заключается в том, что, хотя создание адреса прошло успешно, ответ из выборки MyAddress показывает предыдущие адреса и не обновляет список адресов. я не знаю, есть ли проблема с моим API или мои коды. вот мой код экранов: MyAddress.js

import React,{PureComponent} from 'react';
import {View,Text,FlatList,TouchableOpacity,StyleSheet,Dimensions,RefreshControl} from 'react-native';
import Header from './../../../components/common/Header';
import Icon from 'react-native-vector-icons/FontAwesome5';
import Icons from 'react-native-vector-icons/Ionicons';
import {connect} from 'react-redux';
import Axios from 'axios';
import { UIActivityIndicator } from "react-native-indicators";
import {Toast} from 'native-base';
import AwesomeAlert from 'react-native-awesome-alerts';

const height = Dimensions.get("window").height;
const width = Dimensions.get("window").width;

class MyAddress extends PureComponent{

       state={
            dataSource:[],
            isLoading:false,
            showAlert:false,
            itemId:'',
            switch:false,
            refreshing:false,
        }
        // this.GetData()
   
    // GetData = async() => {
    //     const { phoneNumber, accessToken } = this.props;
    //     this.setState({refreshing:true,switch:false})
    //   await Axios.get(`http://mizbanino.com/api/web/index.php?r=user/get-addresses&username=${phoneNumber}&token=${accessToken}`)
    //         .then(response=>{
    //             this.setState({isLoading:false,refreshing:false,switch:true})
    //             if(response.data.code===1){
    //                 this.setState({dataSource:response.data.data})
    //             }
    //         }).catch(err=>{
    //             this.setState({isLoading:false,refreshing:false,switch:true});
    //             Toast.show({
    //                 text:'خطا در برقراری ارتباط',
    //                 textStyle:{fontFamily:'iranSans',fontSize:15,textAlign:'center'},
    //                 type:'danger',
    //                 duration:2000,
    //                 position:'bottom'
    //             })
    //         })
  
    //     console.log(this.state.dataSource)
        
    //   };
    //   onRefresh=()=> {
    //     this.setState({ dataSource: [] });
    //     this.GetData();
    //   }

    async componentDidMount(){
        const {accessToken,phoneNumber} = this.props;
        this.setState({isLoading:true,switch:false})
      await fetch(`http://mizbanino.com/api/web/index.php?r=user/get-addresses&username=${phoneNumber}&token=${accessToken}`)
        .then(res=>res.json())
        .then(response=>{
            this.setState({isLoading:false,switch:true})
            console.log(response)
            if(response.code==1){
                this.setState({dataSource:response.data})
            }
        }).catch(err=>{
            this.setState({isLoading:false,switch:true});
            Toast.show({
                text:'خطا در برقراری ارتباط',
                textStyle:{fontFamily:'iranSans',fontSize:15,textAlign:'center'},
                type:'danger',
                duration:2000,
                position:'bottom'
            })
        })
        console.log(this.state.dataSource)
    }
    deleteAddressHandler= async()=>{
        const {phoneNumber,accessToken} = this.props;
        const {itemId} = this.state;

       await Axios.get(`http://mizbanino.com/api/web/index.php?r=user/delete-address&username=${phoneNumber}&token=${accessToken}&id=${itemId}`)
        .then(response=>{
            if(response.data.code==1){
                this.setState({dataSource:this.state.dataSource.filter(item=>{
                    return item.id!=itemId
                })})
                Toast.show({
                    text:'با موفقیت حذف شد',
                    textStyle:{fontFamily:'iranSans',fontSize:15,textAlign:'center'},
                    type:'success',
                    duration:2000,
                    position:'bottom'
                })
                this.setState({showAlert:false})
            }

        }).catch(err=>{
            console.log(err)
            Toast.show({
                text:'خطا در برقراری ارتباط',
                textStyle:{fontFamily:'iranSans',fontSize:15,textAlign:'center'},
                type:'danger',
                duration:2000,
                position:'bottom'
            })
        })
    }
    render(){
        if (this.state.isLoading) {
            return <UIActivityIndicator color="blue" size={40} count={10} />;
          }
        return(
            <View style={{flex:1,backgroundColor:'#E9E9E9'}}>
            <Header headerText='آدرس های من' name='md-arrow-back' color='white' onPress={()=>this.props.navigation.navigate('EditProfile')} />
            <FlatList
            data={this.state.dataSource}
            extraData={this.state}
            showsVerticalScrollIndicator={false}
            keyExtractor={(item,index)=>index.toString()}
            // refreshControl={
            //     <RefreshControl
            //     refreshing={this.state.refreshing}
            //     onRefresh={this.onRefresh}
            //     />
            //   }
            ListEmptyComponent={()=>(
                <View style={{flex:1,alignItems:'center'}}>
                    <Icon name='address-card' size={140} color='#BBBBBB' style={{marginBottom:20,marginTop:30}}/>
                    <Text style={{fontFamily:'iranSans',fontSize:15,marginTop:20}}>آدرسی را اضافه نکرده اید</Text>
                </View>
            )}
            renderItem={({item})=>{
                return(
                    <View style={styles.itemContainer}>
                        <View style={{flex:1,justifyContent:'center',alignItems:'center',borderTopLeftRadius:5,borderBottomLeftRadius:5}}>
                        <Icons name="ios-trash" color='red' size={25} onPress={()=>this.setState({showAlert:true,itemId:item.id})}/>
                        </View>
                        <View style={{flex:0.5,justifyContent:'center',alignItems:'center'}}>
                        <Icon name='pen' color='gray' size={20} onPress={()=>this.props.navigation.navigate('EditAddress',{
                            recieverName:item.reciever_name,
                            zipCode:item.zip_code,
                            id:item.id,
                            address:item.address,
                            city:item.city,
                            state:item.state,
                            user:item.user
                        })} />
                        </View>
                        <View style={{flex:7,justifyContent:'center',alignItems:'center',}}>
                        <Text style={{fontFamily:'iranSans',marginRight:2,marginLeft:2,fontSize:12}}>
                         {item.city_title} {item.address} </Text>
                        </View>
                        <View style={{flex:1,justifyContent:'center',alignItems:'center',borderTopRightRadius:5,borderBottomRightRadius:5}}>
                        <Icon name='crosshairs' size={20} color='green'/>
                        </View>  
                    </View>
                )
            }}
            />
            <TouchableOpacity style={styles.addButton} onPress={()=>this.props.navigation.navigate('CreateAddress')}>
                <Text style={{fontFamily:'iranSans',fontSize:16,color:'white',marginRight:10}}>افزودن آدرس جدید</Text>
                <Icons name='md-add' size={27} color='white' />
            </TouchableOpacity>
            <AwesomeAlert
          show={this.state.showAlert}
          showProgress={false}
          titleStyle={{fontFamily: 'iranSans',fontSize: 15}}
          messageStyle={{fontFamily: 'iranSans',fontSize: 13}}
          title="حذف آدرس"
          message="آدرس مورد نظر حذف شود؟ "
          closeOnTouchOutside={true}
          closeOnHardwareBackPress={false}
          showCancelButton={true}
          showConfirmButton={true}
          cancelText="خیر"
          confirmText="بله، حذفش کن"
          confirmButtonColor="#27E300"
          cancelButtonColor='#FF0017'
          cancelButtonTextStyle={{fontFamily: "iranSans",color: 'white',fontSize: 15}}
          confirmButtonTextStyle={{fontFamily: "iranSans",color: 'white',fontSize: 15}}
          onCancelPressed={() =>this.setState({showAlert:false})}
          onConfirmPressed={this.deleteAddressHandler}
        />
            </View>
        )
    }
}

const styles = StyleSheet.create({
    addButton:{
        width:'100%',
        height: 0.07*height,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#10988E',
        flexDirection: 'row'
    },
    itemContainer:{
        width:'95%',
        height: 50,
        backgroundColor: 'white',
        flexDirection: 'row',
        alignSelf: 'center',
        marginTop: 5,
        elevation:2,
        borderRadius: 5
    }

})

const mapStateToProps = state => {
    return {
      phoneNumber: state.login.phoneNumber,
      accessToken: state.login.accessToken,
      mainAddress:state.editor.mainAddress
    };
  };
  
export default connect(mapStateToProps,null) (MyAddress);

введите код здесь

import React, { Component } from "react";
import {
  View,
  Text,
  FlatList,
  TouchableOpacity,
  StyleSheet,
  Dimensions,
  ScrollView,
  TextInput,
  Picker
} from "react-native";
import Header from "./../../../components/common/Header";
import Icon from "react-native-vector-icons/FontAwesome5";
import Icons from "react-native-vector-icons/Ionicons";
import { connect } from "react-redux";
import * as actionTypes from "./../../../store/Actions";
import Axios from "axios";
import { UIActivityIndicator } from "react-native-indicators";
import {Toast} from 'native-base';


const height = Dimensions.get("window").height;
const width = Dimensions.get("window").width;

class CreateAddress extends Component {
    state={
        StateSelector:'',
        citySelector:'',
        isLoading:false,
        address:"",
        zipcode:"",
        reciever:'',
        totalNewAddress:[]
    }

  CreateNewAddressHandler = async() => {
    const {accessToken,phoneNumber} = this.props;
    const {StateSelector,citySelector,address,zipcode,reciever} = this.state;
    // this.setState({isLoading:true})
    // this.setState({totalNewAddress:this.state.totalNewAddress.push({phone:phoneNumber,state:1,city:1,reciever_name:reciever,address:address,zip_code:zipcode})})
    // let newAddress = this.state.totalNewAddress[0];
    // this.props.onNewAddress(newAddress);
   await fetch(
      `http://mizbanino.com/api/web/index.php?r=user/create-address&username=${phoneNumber}&token=${accessToken}&state=1&city=1&address=${address}&default=0&phone=${phoneNumber}&reciever_name=${reciever}&zip_code=${zipcode}`
      ,{method:'GET'}
    ).then(res=>res.json())
    .then(response=>{
        this.setState({isLoading:false,address:'',zipcode:'',reciever:'',totalNewAddress:[]})
        console.log(response)
        if(response.code==1){
          fetch(`http://mizbanino.com/api/web/index.php?r=user/get-addresses&username=${phoneNumber}&token=${accessToken}`)
          .then(res=>res.json())
          .then(response=>{
            if(response.code==1){
               console.log(response.data)
            }
        }).catch(err=>{
            this.setState({isLoading:false,switch:true});
            Toast.show({
                text:'خطا در برقراری ارتباط',
                textStyle:{fontFamily:'iranSans',fontSize:15,textAlign:'center'},
                type:'danger',
                duration:2000,
                position:'bottom'
            })
        })
            Toast.show({
                text:
                  "آدرس با موفقیت افزوده شد",
                textStyle: {
                  fontFamily: "iranSans",
                  fontSize: 15,
                  textAlign: "center"
                },
                type:'success',
                duration: 1500,
                position: "bottom"
              });
              this.props.navigation.navigate('MyAddress')
        }
    }).catch(err=>{
        this.setState({isLoading:false})
        Toast.show({
            text:'خطا در برقراری ارتباط',
            textStyle:{fontFamily:'iranSans',fontSize:15,textAlign:'center'},
            type:'danger',
            duration:2000,
            position:'bottom'
        })
    })
  };
  render() {
    if (this.state.isLoading) {
        return <UIActivityIndicator color="blue" size={40} count={10} />;
      }
    return (
      <View style={{ flex: 1, backgroundColor: "#E9E9E9" }}>
        <Header
          headerText="افزودن آدرس"
          name="md-arrow-back"
          color="white"
          onPress={() => this.props.navigation.navigate("MyAddress")}
        />
        <ScrollView style={{ flex: 1, backgroundColor: "#E9E9E9" }}>
          <View style={styles.titleTextHolder}>
            <Text style={styles.TitleText}>
              لطفا آدرس دقیق خود را وارد نمایید
            </Text>
            <Text style={styles.TitleText}>
              سفارش شما به این آدرس ارسال خواهد شد
            </Text>
          </View>
          <Text style={styles.modalText}>نام گیرنده</Text>
          <TextInput
            style={styles.modalInput}
            value={this.state.reciever}
            onChangeText={reciever => this.setState({reciever})}
          />
          <Text style={styles.modalText}>استان</Text>
          <View style={styles.modalInput}>
          <Picker
            selectedValue={this.state.StateSelector} 
            style={{width:'100%',height:'100%'}} 
              mode="dropdown"
              onValueChange={(itemValue, itemIndex) => this.setState({ StateSelector: itemValue })}
              >
              <Picker.Item label='تهران' value={1} key={1} />
            </Picker>
            </View>
          <Text style={styles.modalText}>شهر</Text>
          <View style={styles.modalInput}>
          <Picker
            selectedValue={this.state.citySelector} 
            style={{width:'100%',height:'100%'}} 
              mode="dropdown"
              onValueChange={(itemValue, itemIndex) => this.setState({ citySelector: itemValue })}
              >
              <Picker.Item label='تهران' value={1} key={1} />
            </Picker>
            </View>
          <Text style={styles.modalText}>آدرس دقیق</Text>
          <TextInput
            style={[styles.modalInput, { height: 100 }]}
            value={this.state.address}
            onChangeText={address => this.setState({address})}
            multiline={true}
            textAlignVertical="top"
          />
          <Text style={styles.modalText}>کد پستی</Text>
          <TextInput
            style={[styles.modalInput, { textAlign: "left",marginBottom:20 }]}
            value={this.state.zipcode}
            onChangeText={zipcode => this.setState({zipcode})}
            placeholder="کد پستی خود را به صورت اعداد پشت سرهم بنویسید"
            keyboardType="numeric"
          />
          
        </ScrollView>
        <TouchableOpacity style={styles.addButton} onPress={this.CreateNewAddressHandler}>
          <Text
            style={{
              fontFamily: "iranSans",
              fontSize: 16,
              color: "white",
              marginRight: 10
            }}
          >
            ثبت آدرس جدید
          </Text>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  titleTextHolder: {
    width: "80%",
    height: 0.1 * height,
    justifyContent: "center",
    alignItems: "center",
    alignSelf: "center"
    // marginTop: 0.05 * height
  },
  TitleText: {
    fontFamily: "iranSans",
    fontSize: 14,
    textAlign: "center",
    marginTop: 5
  },
  modalText: {
    fontFamily: "iranSans",
    fontSize: 16,
    marginRight: 25,
    marginTop: 5
  },
  modalInput: {
    width: "80%",
    height: 45,
    borderRadius: 4,
    borderWidth: 1,
    borderColor: "gray",
    textAlign: "left",
    alignSelf: "center",
    elevation: 1,
    marginTop: 5,
    backgroundColor: "white",
    fontFamily: "iranSans"
  },
  addButton: {
    width: "100%",
    height: 0.07 * height,
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: "#10988E"
  },
});

const mapStateToProps = state => {
  return {
    phoneNumber: state.login.phoneNumber,
    accessToken: state.login.accessToken,
    mainAddress:state.editor.mainAddress
  };
};

const mapDispatchToProps = dispatch => {
  return {
      onNewAddress:(newAddress)=>dispatch({type:actionTypes.MAINADDRESS,newAddress})
  };
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(CreateAddress);
...