'Can't update a spesific document on Firestore using React Native
I am trying to develop a mobile app with React Native using Firestore as a database. I'm trying to update a specific document when the "handleLike" function is called. I've passed the id of the posts through handleLike function. I'm trying to update the "comment" field for the sake of the trial. The problem is it updates all of the documents in the database. Also handleLike function is called without me pressing the like button whenever I refresh the page. I get that it is in a loop but I couldn't figure out what I'm doing wrong. I would very much appreciate your help. I have added screenshots of the database and the console.
import { React, useState, useEffect } from "react";
import {
View,
Text,
StyleSheet,
Image,
FlatList,
TouchableOpacity,
} from "react-native";
import { Ionicons, MaterialIcons } from "@expo/vector-icons";
import { useNavigation } from "@react-navigation/core";
import { auth, storage, firestore,firebase } from "../firebase";
import { preventAutoHideAsync } from "expo-splash-screen";
import moment from 'moment';
function Feed() {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(true);
const [userData, setUserData] = useState(null);
//const [deleted, setDeleted] = useState(false);
const fetchPosts = async () => {
try {
const list = [];
const profileRef = firestore.collection("users").doc(auth.currentUser.uid);
const doc = await profileRef.get();
await firestore
.collection("posts")
.orderBy('postTime', 'desc')
.get()
.then((querySnapshot) => {
console.log("Total Posts: ", querySnapshot.size);
querySnapshot.forEach((doc) => {
const pId = doc.id
const {
userId,
userName,
userSurname,
post,
postImg,
postTime,
userImg,
likes,
comments,
likeByUsers } = doc.data();
list.push({
id: pId,
userId,
userName,
userSurname,
userImg:userImg,
post,
postImg,
postTime: postTime,
liked: false,
likes,
comments,
likeByUsers,
});
});
});
setPosts(list);
if (loading) {
setLoading(false);
}
console.log("Posts: ", posts);
} catch (e) {
console.log(e);
}
};
useEffect(() => {
fetchPosts();
}, []);
const renderPost = (posts) => {
const handleLike = (id) => {
console.log(id)
firestore.collection('posts')
.doc(id)
.update({
comment: "tryout 2"
})
}
return (
<View style={styles.feedItem}>
<Image source={{uri: posts.userImg}} style={styles.avatar} />
<View style={{ flex: 1 }}>
<View
style={{
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
}}
>
<View>
<Text style={styles.name}>{posts.userName} {posts.userSurname}</Text>
<Text style={styles.timestamp}>{moment(posts.postTime.toDate()).fromNow()}</Text>
</View>
<MaterialIcons name="expand-more" size={24} color="#73788B" />
</View>
<Text style={styles.post}>{posts.id}</Text>
<Image
source={{uri: posts.postImg}}
style={styles.postImage}
resizeMode="cover"
/>
<View style={{ flexDirection: "row" }}>
<TouchableOpacity onPress={handleLike(posts.id)}>
<Ionicons
name="heart-outline"
size={24}
color="#73788B"
style={{ marginRight: 16 }}
/>
</TouchableOpacity>
<Ionicons name="chatbox-outline" size={24} color="#73788B" />
</View>
</View>
</View>
);
};
return (
<View style={styles.container}>
<View style={styles.header}>
<Text style={styles.headerTitle}>Feed</Text>
<TouchableOpacity style={styles.addButton}>
<Ionicons name="add-circle" size={32} color="black" />
</TouchableOpacity>
</View>
<FlatList
style={styles.feed}
data={posts}
renderItem={({ item }) => renderPost(item)}
keyExtractor={(item) => item.id}
showsVerticalScrollIndicator={false}
></FlatList>
</View>
);
}
const styles = StyleSheet.create({
addButton: {
position: "absolute",
right: 30,
top: 60,
},
container: {
flex: 1,
backgroundColor: "#EBECF4",
},
header: {
paddingTop: 64,
paddingBottom: 16,
backgroundColor: "#FFF",
alignItems: "center",
justifyContent: "center",
borderBottomWidth: 1,
borderBottomColor: "#EBECF4",
shadowColor: "#454D65",
shadowOffset: { height: 5 },
shadowRadius: 15,
shadowOpacity: 0.2,
zIndex: 10,
},
headerTitle: {
fontSize: 20,
fontWeight: "500",
},
feed: {
marginHorizontal: 16,
},
feedItem: {
backgroundColor: "#FFF",
borderRadius: 5,
padding: 8,
flexDirection: "row",
marginVertical: 8,
},
avatar: {
width: 36,
height: 36,
borderRadius: 18,
marginRight: 16,
},
name: {
fontSize: 15,
fontWeight: "500",
color: "#454D65",
},
surname: {
fontSize: 15,
fontWeight: "500",
color: "#454D65",
},
timestamp: {
fontSize: 12,
color: "#808588",
marginTop: 4,
},
post: {
marginTop: 16,
fontSize: 14,
color: "#838899",
},
postImage: {
width: 267,
height: 150,
borderRadius: 5,
marginVertical: 16,
},
});
export default Feed;
Console Screenshot:

Firestore Database Screenshot:

Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
