我有一个带有firestore数据库的原生react应用程序。我想通过添加个人资料图片来更新用户资料。在我的控制台上,我获得了更新成功,但是用户的数据通常不会在数据库中更新。所以每当我刷新的时候,图片就消失了。我的代码如下:
const You = (props) => {
const dispatch = useDispatch();
const user = useSelector(currentUser);
const { name, department, photoURL } = user;
const [modalVisible, setModalVisible] = useState(false)
const [selectedImage, setSelectedImage] = useState(null)
let openImagePickerAsync = async () => {
let permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (permissionResult.granted === false) {
alert("Permission to access camera roll is required!");
return;
}
let pickerResult = await ImagePicker.launchImageLibraryAsync();
if (pickerResult.cancelled === true) {
return;
}
setSelectedImage(pickerResult.uri);
}
const uploadProfilePicture = async() => {
if (selectedImage == null) {
return null;
} else {
const response = await fetch(selectedImage);
console.log(response)
const blob = await response.blob();
const childPath = `profilePicture/${firebase.auth().currentUser.uid}/${Math.random().toString(36)}`
const task = firebase
.storage()
.ref()
.child(childPath)
.put(blob);
const taskProgress = (snapshot) => {
console.log('Transferred: ', snapshot.bytesTransferred)
}
const taskCompleted = () => {
task.snapshot.ref.getDownloadURL()
.then((snapshot) => {
console.log('snap ',snapshot);
console.log('Done')
saveProfilePicture(snapshot)
})
}
const taskError = (snapshot) => {
console.log('Error: ', snapshot)
}
task.on("state_changed", taskProgress, taskError, taskCompleted)
}
}
const saveProfilePicture = (profilePictureURL) => {
const userProfile = firebase.auth().currentUser;
userProfile.updateProfile({
photoURL: profilePictureURL
}).then(() => {
console.log("status: " + 'update success');
dispatch(login({
photoURL: profilePictureURL
}))
}).catch((error) => {
console.log("error: ",error)
});
}
useEffect(() => {
uploadProfilePicture();
}, [selectedImage])
return (
<SafeAreaView style={styles.container}>
<View style={{justifyContent: 'center', alignItems: 'center', marginVertical: 5}}>
<View style={{borderColor: purple, borderRadius: 4}}>
<Avatar
rounded
size="xlarge"
title={extractInitials(name)}
source={{
uri: photoURL,
}}
/>
<Ionicons
name={
Platform.OS === 'ios'
? 'ios-camera'
: 'md-camera'
}
color={purple_70}
size={26}
style={styles.icon}
onPress={() =>
openImagePickerAsync()
}
/>
</View>
<View style={{ justifyContent: 'center', alignItems: 'center', marginTop: 5 }}>
<Text style={{fontWeight: 'bold', color: darkerPurple}}>{name}</Text>
<Text>Department: {convertToUppercase(department)}</Text>
</View>
</View>
{/* TODO: List archived issues here */}
{/* <View style={{marginVertical: 12}}>
<Text style={styles.boldText}>
Archived Issues
</Text>
<View style={{backgroundColor: white, paddingVertical: 8}}>
<Text>List archived issues here</Text>
</View>
</View> */}
<View style={{marginVertical: 12}}>
<Text style={styles.boldText}>
Help
</Text>
<View style={{backgroundColor: white, paddingVertical: 10}}>
{/* {showBox && <View style={styles.box}></View>} */}
<View style={styles.helpItem}>
<MaterialCommunityIcons
name="card-account-phone"
size={18}
color={purple_80}
style={{paddingRight: 12}}
/>
<Pressable onPress={() => navigation.navigate("Contact Us")}>
<Text>Contact us</Text>
</Pressable>
</View>
<View style={styles.helpItem}>
<MaterialCommunityIcons
name="comment-question"
size={18}
color={purple_80}
style={{paddingRight: 12}}
/>
<Pressable onPress={() => navigation.navigate("Faq")}>
<Text>Faq</Text>
</Pressable>
</View>
<View style={styles.helpItem}>
<MaterialCommunityIcons
name="file-document-outline"
size={18}
color={purple_80}
style={{paddingRight: 12}}
/>
<Pressable onPress={() => navigation.navigate("Terms and Conditions")}>
<Text>Terms & conditions</Text>
</Pressable>
</View>
</View>
</View>
<View style={styles.signOut}>
<MaterialCommunityIcons
name="logout"
size={18}
color={red}
style={{paddingRight: 12}}
/>
<Text
style={[styles.boldText, {color: red}]}
onPress={onSignOut}
>
Sign Out
</Text>
</View>
<View style={styles.signOut}>
<MaterialCommunityIcons
name="delete"
size={18}
color={red}
style={{paddingRight: 12}}
/>
<Text
style={[styles.boldText, {color: red}]}}
>
Delete account
</Text>
</View>
</SafeAreaView>
);
}我的redux会更新,但firestore数据不会。拜托,我到底搞错了什么?
发布于 2021-09-19 08:51:16
这里有一些代码中的错误和一些误解。首先是代码。
您可以这样调用您的函数
uploadProfilePicture();但是您希望在这里有一个profilePictureURL
const saveProfilePicture = (profilePictureURL) => {此外,您只更新auth个人资料图片,而不更新数据库中的任何内容。
下面是一个示例,它应该可以正常工作,并且可以执行您期望的操作:
const saveProfilePicture = (profilePictureURL) => {
const userProfile = firebase.auth().currentUser;
var db = firebase.firestore();
//Here we save the picture to the user auth
userProfile
.updateProfile({
photoURL: profilePictureURL,
})
.then(() => {
console.log("status: " + "update success");
// Here we save to the firestore database
db.collection("users") // Change this path to something else if you want
.doc(firebase.auth().currentUser.uid)
.set(
{
photoURL: profilePictureURL,
},
{ merge: true }
)
.then(() => {
dispatch(
login({
photoURL: profilePictureURL,
})
);
});
})
.catch((error) => {
console.log("error: ", error);
});
};
useEffect(() => {
// You forgot to add selctedImage here
uploadProfilePicture(selectedImage);
}, [selectedImage]);您可以根据需要更改数据库中的路径,但请确保您的数据库规则允许您在其中保存某些内容。
发布于 2021-09-19 20:27:26
查看我对saveProfilePicture函数所做的更改。感谢大家的贡献。
const saveProfilePicture = (profilePictureURL) => {
const userProfile = firebase.auth().currentUser;
return firebase.firestore()
.collection("users")
.doc(firebase.auth().currentUser.uid)
.update({
photoURL: profilePictureURL
})
.then(() => {
console.log("Update success");
})
.catch((error) => console.error("Error: ", error));
}https://stackoverflow.com/questions/69237644
复制相似问题