Home > OS >  I have a problem with connecting between 'onValue' syntax and 'set' syntax in fi
I have a problem with connecting between 'onValue' syntax and 'set' syntax in fi

Time:09-06

var temp_index = 1
var starCountRef = ref(db, '1/'  temp_index);
onValue(starCountRef, (snapshot) => {
    var data = snapshot.val();
})

set(ref(db, '1/'   temp_index), {
   "0": data[0],
   "1": data[1]  ,
   "2": data[2]
});

I want to get the data from realtime database, and then update newly to database. So, my goal is to connect onValue syntax and set syntax in one sentence. I infer that await or then syntax will be needed, but I don't know how to do it. The following code makes error because 'data' is defined only in onValue function, and I do not want to make it global variable like using window. Please Help!

CodePudding user response:

Something like this should do the trick:

var temp_index = 1
var starCountRef = ref(db, '1/'  temp_index);
get(starCountRef).then((snapshot) => {
    var data = snapshot.val();

    set(ref(db, '1/'   temp_index), {
       "0": data[0],
       "1": data[1]  ,
       "2": data[2]
    });
})
  • Related