简体   繁体   中英

How to set Firebase snapshot data into array in sessionStorage

var db1 = firebase.firestore();//API firestore database
var docRef1 = db1.collection("SuccessTransaction");
var showSeat = docRef1.get().then(function(snapshot){
    snapshot.forEach(function(doc){
    if(doc.exists){
            alert(doc.data().Seat);
            sessionStorage.setItem("routeUnavailableSeat", JSON.stringify(doc.data().Seat));

        }else{
            alert("No such documet!");
        }
});
}).catch(function(error){
    alert("Error getting document!", error);
});

I had a problem with this kind of situation. My intention was to set my snapshot value and set it into sessionStorage. The problem is after the system run, it will replace the old data and replace the new data. How can I using array or other method in order to keep all my data in sessionStorage?

The local storage API (that session storage is based on) can only store string values. So to store your values as an array, you will need to encode the array in a string.

Aside from that, it's a matter of getting the current value, parsing it, and then adding it back into session storage:

if(doc.exists){
  let value = sessionStorage.getItem("routeUnavailableSeat");
  let seats = current ? JSON.parse(current) : [];
  seats.push(doc.data().Seat)
  sessionStorage.setItem("routeUnavailableSeat", seats);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM