'Firebase RTDB updating - Array Duplicates

I have a rather simple application that allows people to post some posts like Instagram.

Im working on the like functionality. heres what ive done so far.

const [posts, setPosts] = useState([]);

my useEffect fetching all the data.

useEffect(() => {
  let tempArray = [];
  const posts = ref(db, 'posts/');
  onValue(posts, (snapshot) => {
    snapshot.forEach((childSnapshot) => {
      const childKey = childSnapshot.key;
      const childData = childSnapshot.val();
      let tempObject = {
        documentID: childData.documentID,
        username: childData.username,
        profile_picture: childData.profile_picture,
        imageUrl: childData.imageUrl,
        postText: childData.postText,
        datePosted: childData.datePosted,
        uploadFilter: childData.uploadFilter,
        likes: childData.likes
      }

      tempArray.push(tempObject)
    });
    var newArrayDataOfOjbect = Object.values(tempArray)
    setPosts(newArrayDataOfOjbect)
  });

}, [])

Works great. However, my like function works, but i need to make it so it just updates the value of the certain object in my frontend, and not make an entire new object. It works great on the firebase part, however, in the frontend it just makes a duplicate of that post being updated. Im pretty sure its because of my useEffect, since it executes every time something been changed.

my like event below.

const likeEvent = (obj) => {
  const dbRef = ref(getDatabase());

  const postData = {
    datePosted: obj.datePosted,
    documentID: obj.documentID,
    imageUrl: obj.imageUrl,
    likes: obj.likes + 1,
    postText: obj.postText,
    profile_picture: obj.profile_picture,
    uploadFilter: obj.uploadFilter,
    username: obj.username
  };

  const updates = {};

  get(child(dbRef, `posts/${obj.documentID}`)).then((snapshot) => {
    if (snapshot.exists()) {
      console.log(snapshot.val());
      console.log(snapshot.val().likes + 1)
      updates['/posts/' + obj.documentID] = postData;
      return update(ref(db), updates);
    } else {
      console.log("No data available");
    }
  }).catch((error) => {
    console.error(error);
  });

Any help I'm truly grateful for!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source