简体   繁体   中英

How to call the function only once, when i make a login/open app

I have got a function and need only once call it, when the suer make login.

 function Read(){
    const [counter, setCounter] = useState(1);
    const starCountRef = ref(db, 'users/' + user.localId);
    
    onValue(starCountRef, (snapshot) => {
        const data = snapshot.val();
        setCounter(data.countTrains);   
    });
  }

  useEffect(() => {
      Read();
      console.log('counter:', counter)
  },[]);

I need to write data here into counter variable

I am not sure what you want to achieve, here is your function

const functionThatIsCalledOnlyOnce = ( counterValue ) => {
   setCounter(counterValue)
}

When you want to call this function? if you want to call it only once, when app open put it in useEffect:

  useEffect(()=>{
   functionThatIsCalledOnlyOnce(1);
  },[]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM