How to get child - Firebase - javascript

how to get name child
const ref = firebase.database().ref('order/');
const dbref = ref.child('items');
ref.on('child_added', data => {
console.log(data.key, data.val().name);
});

Your code:
const ref = firebase.database().ref('order/');
const dbref = ref.child('items');
Sets up a reference to /order/items. There is no such location in the data you show.
What you want instead:
const ref = firebase.database().ref('order/');
ref.on('child_added', snapshot => {
// snapshot now contains the data of -KmDWQ...
snapshot.child("items").forEach((itemSnapshot) => {
console.log(itemSnapshot.key, itemSnapshot.val().name);
});
});

Related

Creating an Array of Likes from Javascript Functions

These are parts of my entire code. So what I am trying to do is create separate arrays of the values I like or dislike and output them in my html File onclick. I tried to create an empty array and push value but my final array ends up empty.
Script.js
const showRandomMovie = async() => {
const movieInfo = document.getElementById('movieInfo');
if (movieInfo.childNodes.length > 0) {
clearCurrentMovie();
};
const movies = await getMovies();
const randomMovie = getRandomMovie(movies);
const info = await getMovieInfo(randomMovie);
displayMovie(info);
};
playBtn.onclick = showRandomMovie;
helper.js
const displayMovie = (movieInfo) => {
const moviePosterDiv = document.getElementById('moviePoster');
const movieTextDiv = document.getElementById('movieText');
const likeBtn = document.getElementById('likeBtn');
const dislikeBtn = document.getElementById('dislikeBtn');
// Create HTML content containing movie info
const moviePoster = createMoviePoster(movieInfo.poster_path);
const titleHeader = createMovieTitle(movieInfo.title);
const overviewText = createMovieOverview(movieInfo.overview);
const releaseHeader = createReleaseDate(movieInfo.release_date)
// Append title, poster, and overview to page
moviePosterDiv.appendChild(moviePoster);
movieTextDiv.appendChild(titleHeader);
movieTextDiv.appendChild(overviewText);
movieTextDiv.appendChild(releaseHeader)
showBtns();
likeBtn.onclick = likeMovie;
dislikeBtn.onclick = dislikeMovie;
};
const likeMovie = () => {
clearCurrentMovie();
showRandomMovie();
};
// After disliking a movie, clears the current movie from the screen and gets another random movie
const dislikeMovie = () => {
clearCurrentMovie();
showRandomMovie();
};
Create arrays for the likes and dislikes and push it to an array. Pass it along to your methods.
likeBtn.onclick = () => rateMovie('likes', movieInfo);
dislikeBtn.onclick = () => rateMovie('dislikes', movieInfo);
have the method add it to the array
const ratings = {
likes: [],
dislikes: [],
};
const rateMovie = (type, data) => {
ratings[type].push(data);
clearCurrentMovie();
showRandomMovie();
};

Getting total Number of User Items in Firebase Realtime database in javascript

I have been trying to get amount of users that have same "referralId" in my firebase Realtime database,
users {
AY35bkc5cbkufik8gfe3vjbmgr {
email: james #gmail.com
verify: none
referralid: AY35ja35
}
B16fty9jDchfNgdx7Fxnjc5nxf5v {
email: mobilewisdom #gmail.com
verify: none
referralid: AY35ja35
}
}
How can I use JavaScript to count the amount of account with referralid:AY35ja35
I tried:
const query = ref.orderByChild('referralid').equalTo('AY35ja35');
query.get().then((results) => {
console.log(Object.keys(results.val()).length);
results.forEach((snapshot) => {
console.log(snapshot.key, snapshot.val());
});
});
But am getting this error in my console:
Uncaught TypeError: query.get is not a function
In v8/namespaced syntax that'd be:
const ref = firebase.database().ref('users');
const query = ref.orderByChild('referralid').equalTo('AY35ja35');
const results = await query.get();
console.log(Object.keys(results.val()).length);
results.forEach((snapshot) => {
console.log(snapshot.key, snapshot.val());
});
Or if you're in an environment where await doesn't work:
const ref = firebase.database().ref('users');
const query = ref.orderByChild('referralid').equalTo('AY35ja35');
query.get().then((results) => {
console.log(Object.keys(results.val()).length);
results.forEach((snapshot) => {
console.log(snapshot.key, snapshot.val());
});
});
In v9/modular syntax the equivalent would be:
const ref = ref(getDatabase(), 'users');
const query = query(ref, orderByChild('referralid'), equalTo('AY35ja35'));
const results = await get(query);
console.log(Object.keys(results.val()).length);
results.forEach((snapshot) => {
console.log(snapshot.key, snapshot.val());
});
Or if you're in an environment where await doesn't work:
const ref = ref(getDatabase(), 'users');
const query = query(ref, orderByChild('referralid'), equalTo('AY35ja35'));
get(query).then((results) => {
console.log(Object.keys(results.val()).length);
results.forEach((snapshot) => {
console.log(snapshot.key, snapshot.val());
});
});
Firstly you will have to run a query to get the data from firebase using either firebase package, axios or fetch
Your data is fetched in form of Object containing different objects. You can either user for .. in .. loop to iterate through the object.
var count = 0
for (const user in users) {
if (user.referralid==="AY35ja35") {
count++
}
}
Or use Object.values(object) function to get array of users. Now you can use a JavaScript array function such as map or filter.
by using map. you can do it like this:
var count=0
user.map(user=>{if(user.referralid==="AY35ja35"){count++})
or by using filter
const matchedUsers = user.filter(user=>(user.referralid==="AY35ja35"))
const count = matchedUsers.length
Hope this helps :)

Retrieve data from real time firebase in useEffect return undefined

I tried to implement the followers/following function and it succeeds but, I have a problem retrieving followers and following lists from real-time firebase.
When the user presses on another username followers/following, it sends the uid of the pressed user to this class, then by using the uid followers' list is retrieved and displayed.
The uid is correct at the beginning of the class, but the followers' list returns undefined and sometimes it returns a list on the second save(when I press Ctrl+s).
export default function showFollowers({
navigation,
route
}) {
const [followerslist, setFollowersList] = useState();
const [uid, setuid] = useState(route.params.uid);
const [usersList, setUsersList] = useState([]);
const followersl = [];
// ---snip---
}
HERE, the followers list returned undefined.
useEffect(
() => {
const usersRef1 = firebase.database()
.ref('users/' + uid)
.child("followers");
usersRef1.on('value', async (snapshot) => {
const users1 = snapshot.val();
//const followersl= [];
for (let id in users1) {
followersl.push(users1[id]);
}
await setFollowersList(followersl)
console.log(followerslist) // undefined
console.log(uid) // correct
});
},
[]
);
// Calling second to return info of each follower [profile image,username,name] to be displayed as flat list.
second;
const second = () => {
for (var i = 0; i < followerslist.length; i++) {
getInfo(followerslist[i]);
}
}
const getInfo = (element) => {
const usersRef = firebase.database()
.ref('users')
.orderByChild('usernameLC')
.equalTo(element.toString().toLowerCase());
usersRef.on('value', (snapshot) => {
const users = snapshot.val();
for (let id in users) {
usersList.push(users[id]);
}
setUsersList(usersList);
});
}

Add documentID of fetched document to array in firebase cloud function

I have a cloud function that "Joins" data from a list of documents in a collection.
I then return the result as an array, but I want to return the documentId as well (doc.id) in the list that i return.
How can i do that?
const restData = [];
//const userId = ctx.auth.uid;
const userId = 'dHAP1CNN6LhJWddQoTqyIkqIjhB2'; // !!! TEST ONLY
const all = await db.collection(`/customers/${userId}/lunch_cards`).listDocuments().then((snapshot) => {
snapshot.forEach(doc => {
const nextData = db.collection(`/restaurants`).doc(doc.id).get();
const newData = {...nextData, documentId: doc.id}; <-- This does not work only documentId isout in newData
console.log(util.inspect(newData));
restData.push(nextData);
console.log(doc.id);
});
});
const snaps = await Promise.all(restData);
const responseArray = snaps.map((s) => {return s.data()});
return responseArray;
I solved it!
Solution:
Just adding a new string to the array :)
const responseArray = snaps.map((s) => {
const snapData = s.data();
if (snapData) {
snapData['id'] = s.id;
}
return snapData;
});

Change certain value in all unique keys

So I am trying to code http trigger function which would change the certain value in every unique key (user id). I have written something but the output is not what I need. Instead of changing existing values, it creates new user id.
const functions = require('firebase-functions')
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase)
exports.picksReset = functions.https.onRequest((req, res) => {
const ref = admin.database().ref()
const usersPicked = []
ref.child('users').once('value').then(snap => {
snap.forEach(childSnap => {
ref.child('/users/{userId}').push({picksDone: "0"})
console.log("Changing value...")
})
})
res.send("Done!")
})
An image of my database...
Using .push() creates a new child with a pushId. Instead, use .update(). See details in the documentation here. If you're looking to change the child picksDone in each user, you can do so like this:
const functions = require('firebase-functions')
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase)
exports.picksReset = functions.https.onRequest((req, res) => {
const ref = admin.database().ref()
const usersPicked = []
ref.child('users').once('value').then(snap => {
snap.forEach(childSnap => {
const key = childSnap.key
ref.child(`users/${key}`).update({picksDone: "0"})
console.log("Changing value...")
})
})
res.send("Done!")
})

Categories

Resources