Home > Software design >  Firebase realtime database listener problem
Firebase realtime database listener problem

Time:11-23

So I am using Firebase Realtime Database and I want to remove a listener if there is not yet a database create to avoid error "Cannot read properties of null (reading 'message')" I use the event onValue but i don't know if it is a good idea.

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const database = getDatabase(app);    

// On click send message to database
submit.addEventListener('click', (e) => {

  var message = document.getElementById('message').value;    

  set(ref(database, 'messages'), {
    message: message
  });

  document.getElementById('message').value = "";
});

const newMsg = ref(database, 'messages/');

// Display the message
onValue(newMsg, (data) => {        
  var divData = data.val().message;
  let h1 = document.querySelector("h1");
  h1.textContent = divData;
});

CodePudding user response:

It looks like data.val() doesn't have a value at some point your data.val().message runs. You'll want to detect that in the code, for example with:

onValue(newMsg, (data) => {        
  if (data.exists()) {
    var divData = data.val().message;
    let h1 = document.querySelector("h1");
    h1.textContent = divData;
  }
});
  • Related