I use vuejs for the app and firebase for the database services.
The database structure looks as below:
The initial state of the the app is as follows:
const state :{
newStatus: [],
statuses: [],
initialStatusFetched: false
}
When the app is created the fullowing events are triggered in the created()
lifecycle hook which fetch the statuses from the firebase and add it to the arrays in the initial state mentioned above:
created(){
//fetches initial status and adds it to statuses[ ]
function fetchStatus() {
const ref = firebase.database().ref();
ref.child("allstatuses").once('value', (snapshot) => {
snapshot.forEach((childSnap) => {
let childKey = childSnap.ke;
let childData = childSnap.val();
let statusData = {
key: childKey,
statusVal : childData
}
state.statuses.unshift(statusData);
state.loader = false;
state.initialStatusFetched = true;
});
});
};
//fetches newly added status and adds it to newStatus[ ]
function statusAdded() {
const ref = firebase.database().ref();
ref.child("allstatuses").on('child_added', function(status) {
if(state.initialStatusFetched){
let statusData = {
key: status.key,
statusVal: status.val()
}
state.newStatus.push(statusData);
}
});
};
}
Now using the arrays which gets filled with the events triggered above I populate the page with statuses using the following template:
<template>
<div>
<div>
<!--statuses-->
<div v-for="status in statuses" class="media my-media">
// ommitted all the un-important part
<div class="media-body">
<button @click="addlike(status.key, userStatus.loggedIn)" class="btn my-btn">Like</button>
//displaying number of likes
<span style="margin-right:20px">{{ status.statusVal.likes }}</span>
<button @click="addDislike(status.key, userStatus.loggedIn)" class="btn my-btn">Disike</button>
//displaying number of dislikes
<span>{{ status.statusVal.dislikes }}</span>
</div>
</div>
</div>
</div>
</template>
so now the problem i am facing is
function updateLikes() {
const ref = firebase.database().ref();
ref.child("allstatuses/" + statuskey + "/likes").on('value', (snapshot) => {
// hiw can I fetch the value os statusKey so i can use it above
console.log(snapshot.val());
});
};
how can I get the value of statusKey so I can use it to refer to the node and update the value of likes using the above code?
how do i know which status's likes got updated in the database and where that particular status is in the statuses[ ] , since statuses [ ] gets on added by new statuses?