Home > OS >  How can I call the function once?
How can I call the function once?

Time:12-20

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?

CodePudding user response:

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)
},[]);

CodePudding user response:

useEffect(()=>{
  Read()
},[])

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

  • Related