Home > Software design >  Problem assigning data from onSnapshot firestore to a Vue ref variable
Problem assigning data from onSnapshot firestore to a Vue ref variable

Time:05-06

Me and my friends are using Vue with firestore to create some functionality. This is our first experience using either and we are having some trouble. We are now trying to add a onSnapshot to a doc on firestore and assign said data to a vue ref variable thus making it possible to use a watcher and respond to changes.

As can be seen in the image our doc contains 2 arrays which is the data we need to reach after a change has been observed by the onSnapshot. Our problem is that we dont know how to assign gameData to the appropriate data so that we can reach and use a watcher outside of the function. Datastructure on firestore

export function realTimeGame(lobbyId) {

    const gameCollection = firestore.collection('lobbies/'   lobbyId   '/game_data');

    const gameData = ref([]);
    const unsubscribe = gameCollection.doc('gameThings').onSnapshot(snapshot => { 
        // gameData.value = snapshot.map(document => ({ id: document.id, ...document.data() })) .map is not defined
        gameData.value = snapshot; //this is essentially what we want to do
    });
    onUnmounted(unsubscribe)
    return { gameData }
}

CodePudding user response:

We found a solution:

 export function realTimeGame(lobbyId) {
    const gameData = ref();
    const unsub = onSnapshot(doc(firestore,'lobbies/'   lobbyId   '/game_data/gameThings'),(doc) => {
        gameData.value = { ...doc.data()} 
    })
    onUnmounted(unsub)
    return gameData
}
  • Related