How to get random pushed key from firebase realtime database - javascript

i am about to delete the child -MAkugTU_85UTvn4g9Hn by date(timestamp) and videoId value in folowing image
i tried below code only return the parent called oUi3NI9SdcbCC6v5EmygDNV4lrg1 not the random pushed key, any suggestion will be appreciated. thanks
const uid = firebase.auth().currentUser.uid;
const ref = firebase.database().ref('posts').child(uid);
ref.orderByChild('date').equalTo(date).once("value",snapshot => {
console.log(snapshot.key) // oUi3NI9SdcbCC6v5EmygDNV4lrg1
});

const ref = firebase.database().ref('posts').child(uid);
ref.orderByChild('date').equalTo(date).once("value",snapshot => {
console.log(snapshot.key) // key of parent
snapshot.forEach((childSnapshot) => {
console.log(childSnapshot.key) //here you will get key of each child
}
});
Then by using child key you can do whatever you want to do with it.

Related

mapped button info is out of bounds

function AddDocument(Name, TTid) {
auth.onAuthStateChanged(user => {
if(user) {
const colUser = collection(fsinfo, 'User');
// goes to database colelction "user"
const colUser2 = doc(colUser, user.uid);
// goes to the document in colUser named "one"
const colUser3 = collection(colUser2, 'MoviesLiked');
whenSignedIn.hidden = false;
whenSignedOut.hidden = true;
setDoc(doc(colUser3, Name), {
movieliked: TTid,
})
}
else {
whenSignedIn.hidden = true;
whenSignedOut.hidden = false;
//userDetails.innerHTML = '';
console.log( "while logged out" );
console.log("notloggedin");
}
})
};
// query can either be a title or a tt id
function searchMovie(query) {
const url = `https://imdb8.p.rapidapi.com/auto-complete?q=${query}`;
fetch(url, options)
.then(response => response.json())
.then(data => {
var outname = null;
var outdetail = null;
const movieList = document.querySelector('.movielist');
movieList.addEventListener('click', handleClick);
const list = data.d;
//array of list with data from the movie search
//data.d is the specific datas that is outputted from the api
//list is an array that holds that data
console.log(list)
// ^ will output what list holds
const html = list.map(obj => {
const name = obj.l; // holds the name of movie
outname = name;
const poster = obj.i.imageUrl; // holds the poster, i is the image
const detail = obj.id
outdetail = detail;
return `
<section class="movie">
<img src="${poster}"
width = "500"
height = "800"/>
<h2>${name}</h2>
<section class = "details">${detail}</section>
<button type="button">Movie Details</button>
</section>
`;
}).join('');
// Insert that HTML on to the movie list element
function handleClick(e) {
if (e.target.matches('button')) {
const details = e.target.previousElementSibling;
details.classList.toggle('show');
AddDocument(outname, outdetail);
}
}
movieList.insertAdjacentHTML('beforeend', html);
document.getElementById("errorMessage").innerHTML = "";
})
.catch((error) => {
document.getElementById("errorMessage").innerHTML = error;
});
I have a function that will take search to an API call and then load the info from the API to a list.
It should then output said each of said list using list.map(obj) and each item will have a name, poster, and a button attached to it.
Outside the map I have a function that will react when the button is pressed which will toggle and then load the details of the movie to a database in the AddDocument function. My issue is that I am not sure how to make it so that when the button is pressed AddDocument will add whichever obj.name is connected to the button.
Currently, AddDocument will only add the last item in the list and not the item that I pressed the button for.
I know that it is because the function is outside where the mapping is done, and thus the items that are held in outname, and outdetail are the last items that have been mapped. But I just can't figure out a way to make the button press add the correct document to the database.
(I really didn't want to ask this, but I had spent hours thinking and searching and couldn't seem to find a solution. Thank you for any form of feedback that there may be.)

Problem with sessionStorage: I am not displaying the first item correctly

I am having a problem with sessionStorage; in particular, I want the id of the ads to be saved in the session where the user puts the like on that particular favorite article.
However, I note that the array of objects that is returned contains the ids starting with single quotes, as shown below:
['', '1', '7']
but I want '1' to be shown to me directly.
While if I go into the sessionStorage I notice that like is shown as:
,1,7
ie with the leading comma, but I want it to start with the number directly.
How can I fix this?
function likeAnnunci(){
let likeBtn = document.querySelectorAll('.like');
likeBtn.forEach(btn => {
btn.addEventListener('click', function(){
let id = btn.getAttribute('ann-id');
//sessionStorage.setItem('like', [])
let storage = sessionStorage.getItem('like').split(',');
//console.log(storage);
if(storage.includes(id)){
storage = storage.filter(id_a => id_a != id);
} else {
storage.push(id);
}
sessionStorage.setItem('like', storage)
console.log(sessionStorage.getItem('like').split(','));
btn.classList.toggle('fas');
btn.classList.toggle('far');
btn.classList.toggle('tx-main');
})
})
};
function setLike(id){
if(sessionStorage.getItem('like')){
let storage = sessionStorage.getItem('like').split(',');
if(storage.includes(id.toString())){
return `fas`
} else {
return `far`
}
} else {
sessionStorage.setItem('like', '');
return`far`;
}
}
The main issue you're having is that you're splitting on a , instead of using JSON.parse().
Also, you've got some other code issues and logical errors.
Solution:
function likeAnnunci() {
const likeBtn = document.querySelectorAll('.like');
likeBtn.forEach((btn) => {
btn.addEventListener('click', function () {
let id = btn.getAttribute('ann-id');
//sessionStorage.setItem('like', [])
let storage = JSON.parse(sessionStorage.getItem('like') || '[]');
//console.log(storage);
if (!storage.includes(id)) {
storage.push(id);
}
sessionStorage.setItem('like', JSON.stringify(storage));
console.log(JSON.parse(sessionStorage.getItem('like')));
btn.classList.toggle('fas');
btn.classList.toggle('far');
btn.classList.toggle('tx-main');
});
});
}
More modular and optimal solution:
const likeBtns = document.querySelectorAll('.like');
// If there is no previous array stored, initialize it as an empty array
const initLikesStore = () => {
if (!sessionStorage.getItem('likes')) sessionStorage.setItem('likes', JSON.stringify([]));
};
// Get the item from sessionStorage and parse it into an array
const grabLikesStore = () => JSON.parse(sessionStorage.getItem('likes'));
// Set a new value for the likesStore, automatically serializing the value into a string
const setLikesStore = (array) => sessionStorage.setItem('likes', JSON.stringify(array));
// Pass in a value.
const addToLikesStore = (value) => {
// Grab the current likes state
const pulled = grabStorage();
// If the value is already there, do nothing
if (pulled.includes(value)) return;
// Otherwise, add the value and set the new array
// of the likesStore
storage.push(value);
setLikesStore(pulled);
};
const likeAnnunci = (e) => {
// Grab the ID from the button clicked
const id = e.target.getAttribute('ann-id');
// Pass the ID to be handled by the logic in the
// function above.
addToLikesStore(id);
console.log(grabLikesStore());
btn.classList.toggle('fas');
btn.classList.toggle('far');
btn.classList.toggle('tx-main');
};
// When the dom content loads, initialize the likesStore and
// add all the button event listeners
window.addEventListener('DOMContentLoaded', () => {
initLikesStore();
likeBtns.forEach((btn) => btn.addEventListener('click', likeAnnunci));
});

Get Firebase child value in JavaScript

I want to only get a specific child value from Firebase using JavaScript.
I always get the entire child values.
This is what it looks like:
Child a -
|- fcmToken: 'abcdefg'
Child a -
|- fcmToken: 'hijklmn'
I always get the entire thing. "Child a – fcmToken: 'abcdefg'"
But I only want to get the fcmToken value 'abcdefg' and 'hijklmn'
Ho can I do so?
I tried this:
return admin.database().ref('/fcmToken').once('value', snapshot => {
var uid = snapshot.val();
return admin.database().ref('/fcmToken/' + uid).once('value', snapshot => {
var fcmToken = snapshot.val();
console.log('FCMTOKEN:', fcmToken)
});
But it's not working. Any ideas, how I can only get the desired values 'abcdefg' and 'hijklmn'
After days of trying I have finally found a solution!
Here is what I did:
return admin.database().ref('/fcmToken').once('child_added', snapshot => {
var uid = snapshot.key;
return admin.database().ref('/fcmToken/' + uid + '/fcmToken').once('value', snapshot => {
var fcmToken = snapshot.val();
});
The var fcmToken = snapshot.val(); was the data, I needed and was trying to get.

Socket listener not getting updates from React state

I have a component in which I set my state from the passed parameters to the component
function ChatList({ bookingList, session, setActiveChat, setBookingList, socket }){
const [activeList, setActiveList] = useState(bookingList);
const [defaultList, setDefaultList] = useState(bookingList);
I set the activeList state from the passed params and then on click I update the state in order to show filtered results
const changeTab = (index) => {
if(index === 0){
setActiveList(defaultList);
if(defaultList.length > 0){
setActiveChat(defaultList[0]);
}else{
setActiveChat(null);
}
}else {
let result = bookingList.filter(booking => booking.is_service_provider == false);
setActiveList(result);
if(result.length > 0){
setActiveChat(result[0]);
}else{
setActiveChat(null);
}
}
So ultimately users can filter their chat lists based on the chosen index
And everything works fine, the DOM is updated and if I call the state from a regular function it shows the correct state.
But when I try to update the state from a socket listener I get the original state and not the filtered state
useEffect(() => {
socket.on('notification', (payload) => {
let list_index = activeList.findIndex(obj => obj.id === payload.room);
if(list_index > -1){
let copy = [...activeList];
copy[list_index].latest_message = payload.message;
setActiveList(copy);
}else{
//Handle if user isnt in the correct segment
}
});
},[activeList])
The problem here is the activeList should only have 2 elements after being filtered but in the socket listener it gets the activeList with all the elements as it was before it gets filtered.
I even tested this with a random onclick listener, the onclick function gets the correct state, so why doesn't my socket listener get the updated state?
Thanks
Whenever activeList changes you add a listener but you do not remove the previous handler. It might casue you
So, try using the return of useEffect.
useEffect(() => {
function handler(payload) {....}
socket.on('notification', handler);
return () => socket.off('notification', handler);
}, [activeList]);
In addition when you just want to update the activeList the setter function gets the previous value so you can just use that, and then your effect won't need any dep other than the ref to the setter function.
useEffect(() => {
function handler(payload) {
...
setActiveList((prev) => {
const index = prev.findIndex(obj => obj.id === payload.room);
if (...) return [];
return [];
});
}
socket.on('notification', handler);
return () => socket.off('notification', handler);
}, [setActiveList]);

How to traverse through the auto key generated by firebase push() in React Native?

I have created a search that queries the discogs api for Albums. when I swipe the Album it gets pushed into the realtime database. Firebase auto generates keys for each item pushed which is great, but I am not sure how to handle these keys. How do I get the image url into my require statement? I
here's the function that pushes to the database.
saveToCollection() {
const myFirebaseRef = firebase.database().ref();
myFirebaseRef.push({
albums: `${this.props.album.cover}`
});
}
Any help would be greatly appreciated!
Update with code from comments:
componentWillMount() {
const rootRef = firebase.database().ref();
const albumRef = rootRef.child('albums');
albumRef.once('value', (snapshot) => {
snapshot.forEach((childSnapshot) => {
var childKey = childSnapshot.key;
var childData = childSnapshot.val(); // ... this.setState({albums: childKey.childData}) }); }); }// This is just a sample script. Paste your real code (javascript or HTML) here.
if ('this_is' == /an_example/) {
of_beautifier();
} else {
var a = b ? (c % d) : e[f];
}
You could iterate over the firebase auto generated keys using for...in and push each value in into an array then use the Mustache {{#.}} ... {{/.}} tag pair to iterate over each object in the array.
let arr = [];
for(let autoKey in childData){
arr.push(childData[autoKey]);
}
let tpl = '{{#.}} {{albums}} {{/.}}';
Mustache.render(tpl, arr);

Categories

Resources