skip to Main Content

This is my first application and I’m currently using a real-time database (Firebase). I’m trying to get a value from timeArray[] and have it shown in timeInput.innerHTML when I click the "Save" Button, but then I got an error saying timeArray[] is not defined.

onValue(qualTime, function(snapshot) {
  let timeArray = Object.values(snapshot.val());
});

saveButton.addEventListener("click", function() {
  document.getElementById("timeInput").innerHTML = timeArray[0];
});

I also tried putting the saveButton.addEventListener() in the onValue() but that got the console to throw at me a bunch of errors and the HTML app itself prints out undefined.

2

Answers


  1. The issue you’re facing is due to the scope of the timeArray variable. Currently, timeArray is defined within the onValue function and is not accessible outside of it.

    To make the timeArray freely usable outside of the function, you need to declare it in a higher scope. One way to achieve this is by declaring the timeArray variable outside of both the onValue function and the event listener function.

    Here’s an example of how you can modify your code to make timeArray accessible outside of the onValue function:

    let timeArray = []; // Declare the timeArray in a higher scope
    
    onValue(qualTime, function(snapshot) {
      timeArray = Object.values(snapshot.val());
    });
    
    saveButton.addEventListener("click", function() {
      document.getElementById("timeInput").innerHTML = timeArray[0];
    });
    

    By declaring timeArray outside of both functions, it becomes accessible to both the onValue function and the event listener function. This way, you can populate timeArray within the onValue function and use it in the event listener function.

    Make sure you initialize timeArray as an empty array [] before the onValue function is executed. This way, even if the onValue function hasn’t populated timeArray yet, it will still be defined when accessed in the event listener function.

    Login or Signup to reply.
  2. As per your code, Issue is related to the variable scope. Variables defined with let have block scope. Hence, timeArray will not be accessible outside of onValue function.

    To get rid from this issue, You have to define the timeArray in a scope where it can be accessible from both the places (onValue function and inside click event).

    let timeArray;
    
    onValue(qualTime, function(snapshot) {
      timeArray = Object.values(snapshot.val());
    });
    
    saveButton.addEventListener("click", function() {
      if (timeArray && timeArray.length) {
        document.getElementById("timeInput").innerHTML = timeArray[0];
      }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search