Search code examples
androidreact-nativefirebase-realtime-databasegetdate

React-Native: read timestamp saved on Firebase, after updating it


I update a timestamp in a Firebase server every time I click a button on my react-native app (android). The problem is that, after updating it, I want to read it and set my state with this timestamp.

Here is some code I found on the Internet, it updates the date on Firebase, reach the first 'then' block but then never go on, so never reach the second 'then' block and never show the alert(onlyDate);

I have no error about rules on Firebase, read and write are both available.

getDateServerFirebase = () => {

    let fb_currentTime = firebase.database().ref('currentTime/');
    fb_currentTime.update({ time: firebase.database.ServerValue.TIMESTAMP })
    .then(() => {
      fb_currentTime.once('value').then(function (data) {
          //console.log(data);
          let timestamp = data._value.time;
          let fullDate = new Date(timestamp);
          let onlyDate = fullDate.getDate() + '/' + (fullDate.getMonth()+1) + '/' + fullDate.getFullYear();

          alert(onlyDate);

        }, function serverTimeErr(err) {
          console.log('Could not reach to the server time !');
        });
    }, function (err) {
      console.log ('set time error:', err)
    });
  }

I tried this and still the same problem: writing works, reading not.

setData = () =>{
    firebase.database().ref('prova/').set({
      name:'luis',
      surname:'rew'
    }, function(error) {
      if (error) {
        // The write failed...
      } else {
        // Data saved successfully!
      }
    });
  }

  readData = () =>{
    firebase.database().ref('prova/')
    .once('value')
    .then((data)=>{
      alert(data);
    })
  }

Can someone help me??


Solution

  • The way you access response from firebase function is through running the val(); function on the result.

    change this line

    let timestamp = data._value.time;
    

    into this:

    let timestamp = data.val().time;