Firebase's onValue only get data once and does not update when placed inside a loop in React's useEffect

Viewed 54

My goal is to get multiple data based on a list of data the customer requested so I put the codes inside useEffect. If the array contains the list of things the customer wants, then it grab those data from the server so the user can manipulate it. So far, it works fine but when the database updates, onValue is not triggered to grab the new data to update the render.

Here is my code. Thank you for helping me in advance.

  // Getting data
  useEffect(() => {
    if (empDataArr.length > 1) {
      let fromDay = parseInt(dateHandler(startDate).dateStamp);
      let toDay = parseInt(dateHandler(endDate).dateStamp);
      let tempLogArr = [];
      empDataArr.forEach((emp) => {
        let qLogEvent = query(child(shopRef(shopId), emp.id + "/log_events"), orderByChild("dateStamp"), startAt(fromDay), endAt(toDay));
        
        // This is the part I need help
        onValue(qLogEvent, (snap) => {
          let logEventArr = [];
          let val = snap.val();
          if (val === null) {
          } else {
            Object.keys(val).forEach((key) => {
              let id = key;
              let dateStamp = val[key].dateStamp;
              let direction = val[key].direction;
              let time = val[key].timeStamp + "";
              let timeStamp = time.substring(8, 10) + ":" + time.substring(10, 12);
              logEventArr.push({ direction: direction, timeStamp: timeStamp, dateStamp: dateStamp, id: id });
            });
            tempLogArr.push({
              id: emp.id,
              logEvent: logEventArr,
            });
          }
        });
      });
      setLogDataArr(tempLogArr.map((x) => x));
    }
  }, [empDataArr, shopId, startDate, endDate]);

  useEffect(() => {
    console.log(logDataArr);
  }, [logDataArr]);

I have tried using return onValue() and const logData = onValue() but they do not work (and I do not expect the former one to work either).

0 Answers
Related