generated from ibm-developer-skills-network/coding-project-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSettingsScreen_withstorage.js
152 lines (139 loc) · 4.18 KB
/
SettingsScreen_withstorage.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
// SettingsScreen.js
import React, { useState, useEffect } from 'react';
import { View, Text, Image, StyleSheet, Alert, Pressable } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import { query, where, setDoc, collection, getDocs, addDoc } from 'firebase/firestore';
import { ref, uploadBytes, getDownloadURL } from 'firebase/storage';
import { auth, db, storage } from './firebase';
const SettingsScreen = () => {
const [avatar, setAvatar] = useState(null);
const [userEmail, setUserEmail] = useState('');
const [imageUrl, setImageUrl] = useState('');
// Get the current authenticated user's email
useEffect(() => {
const currentUser = auth.currentUser;
if (currentUser) {
setUserEmail(currentUser.email);
} else {
Alert.alert('User not logged in', 'Please log in to upload an avatar.');
}
}, []);
const fetchAvatar = async () => {
try {
// Create a query to find documents with the specified email
const q = query(collection(db, "avatars"), where("email", "==", auth.currentUser.email));
const querySnapshot = await getDocs(q);
// Check if the query returned any results
if (!querySnapshot.empty) {
querySnapshot.forEach((doc) => {
if(doc.data().avatar) {
setAvatar(doc.data().avatar);
}
});
} else {
console.log("No such document!");
}
} catch (error) {
console.error("Error getting document: ", error);
}
};
useEffect(() => {
fetchAvatar();
}, [avatar]);
// Function to upload the image to Firebase Storage
const uploadImage = async (uri) => {
const response = await fetch(uri);
const blob = await response.blob();
console.log(ref);
const storageRef = ref(storage, `profile_pics/${new Date().getTime()}.jpg`);
// Upload the image
await uploadBytes(storageRef, blob);
const url = await getDownloadURL(storageRef); // Get the download URL
return url; // Return the download URL
};
// Function to pick an image from the device's gallery
const pickImage = async () => {
// Request permission to access the gallery
const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (permissionResult.granted === false) {
alert("Permission to access camera is required!");
return;
}
const result = await ImagePicker.launchImageLibraryAsync();
console.log("result is ",result);
if (!result.canceled) {
const url = await uploadImage(result.assets[0].uri); // Upload the selected image
setImageUrl(url); // Set the image URL
setAvatar(url);
if (!avatar) {
await addDoc(collection(db, "avatars"), {
email:userEmail,
avatar:url
});
} else {
await setDoc(newDocRef, { email: userEmail, avatarUrl: url });
}
}
};
return (
<View style={styles.container}>
<Text style={styles.title}>Settings</Text>
<Pressable onPress={pickImage}>
<View style={styles.avatarContainer}>
{avatar ? (
<Image source={{ uri: avatar }} style={styles.avatar} />
) : (
<Text style={styles.avatarPlaceholder}>Upload Avatar</Text>
)}
</View>
</Pressable>
<Pressable style={styles.button} onPress={pickImage}>
<Text style={styles.buttonText}>Change Avatar</Text>
</Pressable>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
padding: 20,
},
title: {
fontSize: 24,
marginBottom: 20,
fontWeight: 'bold',
},
avatarContainer: {
width: 150,
height: 150,
borderRadius: 75,
backgroundColor: '#ddd',
alignItems: 'center',
justifyContent: 'center',
marginBottom: 20,
},
avatar: {
width: '100%',
height: '100%',
borderRadius: 75,
},
avatarPlaceholder: {
color: '#666',
fontSize: 18,
},
button: {
backgroundColor: 'black',
paddingVertical: 10,
paddingHorizontal: 20,
borderRadius: 8,
alignItems: 'center',
},
buttonText: {
color: 'white',
fontSize: 16,
fontWeight: 'bold',
},
});
export default SettingsScreen;