Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I call the function once?

I have a project in react native and I need to read data from a firebase db in realtime.
I try to:

const [numberTrains, setNumberTrains] = useState(0)
 function Read(){
    const starCountRef = ref(db, 'users/' + user.localId);
    onValue(starCountRef, (snapshot) => {
      const data = snapshot.val();
      setNumberTrains(data.countTrains);   
    });
  }
  Read()
    console.log(numberTrains)

But it throws the exception: Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
And the output looks like:

 LOG  0
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1

How can I read data in numberTrain only once?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use useEffect

const [numberTrains, setNumberTrains] = useState(0)

function Read(){
  const starCountRef = ref(db, 'users/' + user.localId);
  onValue(starCountRef, (snapshot) => {
    const data = snapshot.val();
    setNumberTrains(data.countTrains);   
  });
}

React.useEffect(()=>{
  Read();
  console.log(numberTrains)
},[]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading