Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
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!

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!