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

184
Views
Adding friend in React using Firebase Realtime Database adding multiple friends rather than one

I am currently working on a project using React and Firebase's realtime database and trying to implement a friend network. Currently my issues resides in the following: the user can enter an email into an input. Once they submit this email, a snapshot will be taken of the entire User database and a foreach loop will be used to loop over it until it finds the piece of data that contains the email the user entered (Each user has an email, username, password, and uId field). Once its found, that users data who contains the email that was entered will be copied over into the current users friends list.

While my code should seem to work, there are a lot of weird issues. In one test, I make three accounts, and have one account add the other two. If I make another account, it will sometimes automatically add the previous user's friends to the current user. I've also found one case where when making a new account and adding a new one that already has friends, those user's friends will be added to the current one. I am hopelessly lost as to why this may be happening.

import React, {useState, useEffect} from 'react'
import {db, auth} from '../config/fire'
import Message from './Message';

function AddFriend() {
  
  const [friend, setFriend] = useState("");
  const [text, setText] = useState("");
  let ref = db.ref(`Users`);

  const handleText = (e) => {
      setText(e.target.value);
  }

  function handleSubmit(e)  {
      ref.on('value', (snapshot) => {
        let newFriend = "";
        snapshot.forEach(data => {
          if (data.val().email===text && data.val().email!==auth.currentUser.email)  {
            const newRef = db.ref(`Users/${auth.currentUser.uid}/friends/${data.val().uId}}`);
            newRef.update({email: data.val().email, name: data.val().name, password: data.val().password, uId: data.val().uId});
            setText("")
          }
          
        })
      },[]);
      setText("");
  }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Figured it out. You need to use ref.once instead of ref.on.

about 4 years ago · Juan Pablo Isaza Report
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!