Search code examples
javascriptfirebasegoogle-cloud-firestoresession-storage

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?


Solution

  • 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);
    }