skip to Main Content

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?

2

Answers


  1. 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)
    },[]);
    
    Login or Signup to reply.
  2. useEffect(()=>{
      Read()
    },[])
    

    it will only call one time suggestion if data is only one time put a check for numberTrains length before calling read

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search