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("");
}
Figured it out. You need to use ref.once instead of ref.on.