BoilerLiftUp / src / components / signup / UploadProfilePicture.jsx
UploadProfilePicture.jsx
Raw
import React, { useState } from "react";
import { StyleSheet, SafeAreaView, Text, TextInput, View, Image } from "react-native";
import { Button} from 'native-base';
import { useTheme } from '@react-navigation/native';
import * as ImagePicker from 'expo-image-picker';
import Logo from '../../resources/logo.png';

function UploadProfilePicture({navigation, route}) {
    const { colors } = useTheme();
    const [photoResult, setPhotoResult] = useState('')
    const [picture, setPicture] = useState('');
    let apiUrl = 'https://api.cloudinary.com/v1_1/boilerliftup/image/upload';
    
    const uploadPicture = async () => {
        let base64Img = `data:image/jpeg;base64,${photoResult.base64}`;

        let data = {
            "file": base64Img,
            "upload_preset": "boiler_picture",
        }

        return fetch(apiUrl, {
            body: JSON.stringify(data),
            headers: {
                'content-type': 'application/json'
            },
            method: 'POST',
        }).then(async r => {
            let data = await r.json();
            // setPicUrl(data.secure_url);
            return data.secure_url;
        }).catch(err => console.log(err))
    };
      
    const selectPicture = async () => {
        let result = await ImagePicker.launchImageLibraryAsync({
            mediaTypes: ImagePicker.MediaTypeOptions.All,
            allowsEditing: true,
            aspect: [4, 3],
            quality: 1,
            base64: true
        });

        if (!result.cancelled) {
            setPicture(result.base64);
            setPhotoResult(result);
        }
    };

    async function handleCreateAccount() {
        if (picture != '') {
            await uploadPicture().then((picUrl) => {
                fetch(localhost+'/signup/picture', {
                    method: 'POST',
                    headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify ({
                        username: route.params.username,
                        url: picUrl
                    })
                })
                .then((response) => {
                    if (response.status === 200 || response.status === 201) {
                        // Successful POST
                        console.log('good pictureUpload');
                        alert("Successfully added!")
                        navigation.navigate("HomeWithNav", {
                            username: route.params.username
                        });
                    } else {
                        // Examine the text in the response
                        console.log('issue in pictureUpload. Status code: '+ response.status);
                        alert("Unsuccessful")
                    }
                })
                .catch(function(err) {
                    console.log('Fetch Error :-S', err);
                });
            });
        }
        navigation.navigate("HomeWithNav",
        {
            username: route.params.username
        })
    }
    return (
        <SafeAreaView style={ [styles.screen, {flexDirection:"column"}] }>
            <Text style={ [styles.title, {color: colors.text}] }>Upload a Profile Picture</Text>
            <View style={ styles.profilePosition }>
                <Image style={ styles.profileSize } defaultSource={Logo} source={{uri: 'data:image/jpeg;base64,' + picture}}
                />
            </View>
            <View style={{flexDirection: "row"}}>
                <Button style={ styles.nextButton } onPress={() =>  selectPicture() }>
                    <Text style={ styles.nextText }>Upload Picture</Text>
                </Button>
            </View>
            <View style={{flexDirection: "row"}}>
                <Button style={ styles.nextButton } onPress={handleCreateAccount}>
                    <Text style={ styles.nextText }>Create Account</Text>
                </Button>
            </View>

        </SafeAreaView>
    );
}

const styles = StyleSheet.create({
    screen:{
        marginTop: "20%",
        paddingLeft: "5%",
        paddingRight: "5%",
        paddingBottom: "30%",
        marginLeft: "10%",
        marginRight: "10%"
    },
    title: {
        fontSize: 25,
        fontWeight: "bold",
        marginTop: "10%",
        paddingBottom: "20%",
        textAlign:"left"
    },
    profilePosition: {
        paddingTop: "12%",
        marginBottom: "5%",
        alignItems: "center"
    },
    profileSize: {
        marginTop: "5%",
        aspectRatio: 1,
        width: 200,
        height: 200,
    },
    subtitle: {
        fontSize: 16,
        textAlign:"left",
        fontWeight: "bold",
        color: '#5c5a55'
    },
    input: {
        width: "100%",
        height: 40,
        borderBottomWidth: 1
    },
    nextButton: {
        width: '100%',
        justifyContent: 'center',
        backgroundColor: "#d4911c",
        borderRadius: 10,
        alignItems: "center",
        marginBottom: 10,
        marginTop: 50
    },
    nextText: {
        fontSize: 16,
        fontWeight: "bold",
        color: "white"
    },
});

export default UploadProfilePicture;