Home > Software design >  firebase react for each loop does not end
firebase react for each loop does not end

Time:08-07

I want to get data from firebase real time database and push it in a react array but the snapshot does not end and loops forever

Here is a link for better understanding. The loop should stop after the first iteration: link

full code


function About() {
  let params = useParams();
  const [title, setTitle] = useState('')
  const group = []
  const [theArray, setTheArray] = useState([]);
  const [myArray, setMyArray] = useState([]);
  
  onAuthStateChanged(auth,  (user) => {
      const uid = '';
      var data_list = []

      const db = getDatabase(app)
      const dbRef = ref(getDatabase(app));
      const sth = params.hey
      useEffect({
             get(child(dbRef, `users/${uid}/${params.hey}`)).then((snapshot) => {
        if (snapshot.exists()) {
          console.log('exists')
          var snap = snapshot.val()
          var rows = snap['rows']
          rows.forEach(element => {
            console.log('element', element)
            setMyArray(arr => [...arr, `${arr.length}`]);
      
          });
        } else {
        }
      }
      ).catch((error) => {
      })
}, []);
    
    
  });
  console.log('group', group)
  return (
    <>
      <main>
        <h2>{title}</h2>
        <div>{myArray.map( e =>
          <div>{ e }</div>
        )}
        </div>
              </main>

    </>
  );
}

CodePudding user response:

Calling get retrieves a result only once, so if you get an endless loop it's because the code you shared is being invoked multiple times.

It's hard to say without seeing the context of where this code runs, but most like you have this in the top-level of your component, and you should put it in a useEffect with a dependency array (typically empty).

useEffect(() => {
  ... load from database here
}, []); // empty array = no dependencies, so it runs only once
  • Related