简体   繁体   中英

how do I put iterative statements in useEffect?

    useEffect(()=>{ 

        while(itemlen===0)
        {
                fire.database().ref().child(path)
            .on("value",
            (snapshot)=>{
              let item=snapshot.val()
              console.log(item)
              if(item!==null){
                let array=[];
                Object.
                keys(item)
                .forEach(i=>array.push(item[i]));
                setCard1(array);
            }
            console.log(item,"item")
            if(item!==null)
           { 
            console.log(Object.keys(item).length,"item length")
            itemlen=7  //length of object I get from valid result
            }
             else {itemlen=0}
            })
           } 
            console.log(itemlen,'itemlen') 
      },[prefVar]);

my code inside the for loop selects a random path and retrieve that path only problem is that sometimes the path is empty so I want to use while loop to iterate the code again until I get a valid path.

Problem is that my app freezes when it comes to this part and get stuck.I am guessing it is due while loop inside useEffect and code works fine without while loop but gives empty results somethimes. Is there some better way to do this?

You are creating an infinite loop so it's normal for it to stop.

You should poll the data source from time to time until you get your information. This can be done from inside useEffect .

Try something like this

useEffect(()=>{
  const getData = () => {
    fire.database().ref().child(path)
        .on("value",
        (snapshot)=>{
          let item=snapshot.val()
          console.log(item)
          if(item!==null){
            let array=[];
            Object.
            keys(item)
            .forEach(i=>array.push(item[i]));
            setCard1(array);
         }
         console.log(item,"item")
         if(item!==null)
         { 
          console.log(Object.keys(item).length,"item length")
          itemlen=7  //length of object I get from valid result
          clearInterval(interval) //stop polling for results
         }
         else {itemlen=0}
        })
     }
    const interval = setInterval(getData, TIMEOUT_INTERVAL)
    return () => clearInterval(interval);
  },[prefVar]);

Notice the return statement from useEffect . This is important as the react component may be removed, so we need to cleanup setInterval .

TIMEOUT_INTERVAL is the time, in ms, to wait between calls.

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