Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { Component } from "react";
  2. import { AppRegistry, StyleSheet, AsyncStorage, KeyboardAvoidingView, Image, Text, View, TouchableOpacity } from "react-native";
  3. //import { StackNavigator } from "react-navigation";
  4.  
  5. import styles from './styles';
  6. import stylesModal from '../styles/stylesModal';
  7. import Logo from '../assets/images/logomin.png';
  8. import IconUser from '../assets/images/icons/user.png';
  9. import IconLock from '../assets/images/icons/lock.png';
  10.  
  11. import ImagePicker from 'react-native-image-picker';
  12.  
  13. import { StackNavigator } from "react-navigation";
  14.  
  15. var source2;
  16. var file = new FormData();
  17. const options = {
  18.   title: 'Select Avatar',
  19.   customButtons: [{ name: 'fb', title: 'Choose Photo from Facebook' }],
  20.   storageOptions: {
  21.     skipBackup: true,
  22.     path: 'images',
  23.   },
  24. };
  25.  
  26.  
  27.  
  28.  
  29. export default class PhotoPerfil extends Component {
  30.   constructor(props) {
  31.     super(props);
  32.     this.state = {
  33.       name: '',
  34.       avatarSource: ''
  35. imageBody:''
  36.     };
  37.  
  38.     //this.setState({name: AsyncStorage.getItem('USER')})
  39.   }
  40.  
  41.   static navigationOptions = {
  42.     headerStyle: {
  43.       backgroundColor: "#16a085",
  44.       elevation: null
  45.     },
  46.     header: null,
  47.     headerLeft: null
  48.   };
  49.  
  50.   componentWillMount() {
  51.     this.getToken();
  52.   }
  53.  
  54.   async getToken() {
  55.     let accessToken = '';
  56.     try {
  57.       accessToken = await AsyncStorage.getItem('token') || 'none';
  58.       if(!accessToken) {
  59.         this.props.navigation.navigate('Login');
  60.       } else {
  61.        
  62.           this.setState({accessToken: accessToken});
  63.           console.warn(this.state.accessToken);
  64.       }
  65.     } catch(error) {
  66.         console.log("Something went wrong");
  67.         this.props.navigation.navigate('Login');
  68.     }
  69.   }
  70.  
  71.  
  72.  
  73.  
  74.   capture() {
  75.     ImagePicker.showImagePicker(options, (response) => {
  76.       //console.warn('Response = ', response);
  77.    
  78.       if (response.didCancel) {
  79.         console.log('User cancelled image picker');
  80.       } else if (response.error) {
  81.         console.log('ImagePicker Error: ', response.error);
  82.       } else if (response.customButton) {
  83.         console.log('User tapped custom button: ', response.customButton);
  84.       } else {
  85.         const source = { uri: response.uri };
  86.         source2 = response.path;
  87.    
  88.        const data = new FormData();
  89.         data.append('image', {
  90.           uri: response.uri ,
  91.           type: response.type,
  92.           name: response.fileName,
  93.         });
  94.        
  95.  
  96.  
  97.         // You can also display the image using data    
  98.         this.setState({
  99.           avatarSource: source,
  100.             imageBody: data
  101.         });
  102.       }
  103.     });
  104.   }
  105.   async onRegisterPress() {
  106.     try {
  107.       var userId = AsyncStorage.getItem('userId') || 'none';
  108.       var token = 'Bearer ' + AsyncStorage.getItem('token') || 'none';
  109.       console.log(userId);
  110.     } catch (error) {
  111.       // Error retrieving data
  112.       console.log(error.message);
  113.     }
  114.     try {
  115.       let response = await fetch('http://54.89.116.183:3300/users/regimg', {
  116.                               method: 'POST',
  117.                               headers: {
  118.                                 'Content-Type': 'multipart/form-data',
  119.                                 'Authorization': 'Bearer ' +this.state.accessToken
  120.                               },
  121.                               body: this.state.imageBody,
  122.  
  123.                              
  124.                             });
  125.       let res = await response.json();
  126.       console.warn(response.status);
  127.       if (response.status >= 200 && response.status < 450) {
  128.           //Handle success
  129.           //On success we will store the access_token in the AsyncStorage
  130.           this.props.navigation.navigate("Boiler");
  131.       } else {
  132.           //Handle error
  133.           let error = res;
  134.           throw error;
  135.       }
  136.     } catch(errors) {
  137.       //errors are in JSON form so we must parse them first.
  138.       let formErrors = JSON.parse(errors);
  139.       //We will store all the errors in the array.
  140.       let errorsArray = [];
  141.       for(var key in formErrors) {
  142.         //If array is bigger than one we need to split it.
  143.         if(formErrors[key].length > 1) {
  144.             formErrors[key].map(error => errorsArray.push(`${key} ${error}`));
  145.         } else {
  146.             errorsArray.push(`${key} ${formErrors[key]}`);
  147.         }
  148.       }
  149.       this.setState({errors: errorsArray})
  150.     }
  151.    
  152.   }
  153.  
  154.   render() {
  155.     return(
  156.       <View style={styles.containerRegister}>
  157.         <View style={styles.registerLogo}>
  158.           <Image source={Logo} />
  159.         </View>
  160.         <View style={styles.contentPhoto}>
  161.             <View style={styles.centerView}>
  162.               <Text style={styles.PhotoPageText}>Foto de perfil</Text>
  163.               <Text style={styles.PhotoText}>Escolha uma foto de perfil:</Text>
  164.               <View style={styles.formCenterImg}>
  165.                 <TouchableOpacity style={styles.PhotoNewButton} onPress={() => this.capture()}>
  166.                   <Image source={(this.state.avatarSource) ? this.state.avatarSource : null} style={styles.FormNewPetButtonImage}/>
  167.                 </TouchableOpacity>
  168.               </View>
  169.               <TouchableOpacity style={styles.BoileButton} onPress={() => this.onRegisterPress()}>
  170.                 <Text style={styles.BoileButtonText}>Salvar foto</Text>
  171.               </TouchableOpacity>
  172.               <TouchableOpacity style={styles.BoileButton} onPress={() => this.props.navigation.navigate("Boiler")}>
  173.                 <Text style={styles.BoileButtonText}>Lembrar-me mais tarde</Text>
  174.               </TouchableOpacity>
  175.             </View>
  176.         </View>
  177.       </View>
  178.       );
  179.   }
  180. }
  181.  
  182. AppRegistry.registerComponent("Boiler", () => Boiler);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement