Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
So basically, I can't display the collection on my html. I get a null value error for gamesList. But when I log it to the console, I can see the contents just fine, no problems there.
// get data
db.collection('games').get().then(snapshot => {
setupGames(snapshot.docs);
});
// DOM elements
const gamesList = document.querySelector('.games');
// setup games
const setupGames = (data) => {
let html = '';
data.forEach(doc => {
const game = doc.data();
const li = `
<li>
<div class="collapsible-header grey lighten-4">${game.title}</div>
<div class="collapsible-body white">${game.content}</div>
`;
html += li
});
gamesList.innerHTML = html;
}
So here something goes wrong and for the life of me I can't figure it out.
but when I use this the data does display correctly in the console, title and content:
// setup guides
const setupGames = (data) => {
let html = '';
data.forEach(doc => {
const game = doc.data();
console.log(game);
});
}
I think, when you use get() function on a collection, it already returns you the document list, so you don't need to call snapshot.docs
There's an example here:
https://firebase.google.com/docs/firestore/query-data/get-data#get_all_documents_in_a_collection
If you want to use real time data with snapshots, try it this way:
db.collection('games').onSnapshot(snapshot => {
setupGames(snapshot.docs);
});
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 months ago.
Improve this question
I'm facing a problem in my project, I'm using Nested Children Routing to show data in my project, I want the data of this specific item to be shown once I click the button on it, I did the routing right, it's just I can't get the proper function for the items.
Here's my service
PostsService.service.ts
getPostById(id: string){
let docId = this.afs.collection('posts').doc(id).get()
.subscribe( doc => {
if(doc.exists){
console.log('Document Id => ', doc.id)
console.log('Document data => ', doc.data())
}else {
console.log('Document not found')
}
});
return docId;
}
and Here's my TS function for the single item
.component.ts
posts: Posts[] = [];
post!:any;
constructor(
private PostsService: PostsService,
private route: ActivatedRoute
) {}
ngOnInit(): void {
let id = this.route.snapshot.params['id']
this.PostsService.getPostById(id);
}
You're attempting the get the whole collection with getPostById() and then trying to find a single document from the results. Getting the whole colletion means you will read n amount of times for n amount of documents - which is wasteful and slow.
If you ask something with getPostById() then you should do something with the return as well. Right now your asking, but not doing anything with the return.
How about we just get the single document? It will return an Observable, so we can keep monitoring the document, or just use the face value as it is.
getPostById(id: string) {
const itemDoc = this.afs.doc<any>('posts/' + id);
return itemDoc.valueChanges();
}
And in your component, don't forget to unsubscribe from the Observable.
ngOnInit() {
let id = this.route.snapshot.params['id'];
this.PostsService.getPostById(id).subscribe(post => {
console.log(post);
})
}
I have a map displaying a geoJSON layer using react-leaflet. I am dynamically changing whats rendered using leaflet-draw.
I am using a loop to find the layers which dont meet the criteria, then saving them so i can add them back later as per the code below.
const [removedLayers, setRemovedLayers] = useState([]);
const [removedMarkers, setRemovedMarkers] = useState([]);
const onCreatePolygon = (e) => {
const geojsonLayers = ref.current;
let [tempLayers, tempMarkers] = [[], []];
//remove polygons that meet criteria
geojsonLayers.eachLayer((layer) => {
if (!e.layer.contains(layer.getCenter())) {
tempLayers.push(layer);
layer.remove();
}
});
//remove markers that meet criteria
const markerGroup = markerRef.current;
markerGroup.eachLayer((layer) => {
if (!e.layer.contains(layer.getLatLng())) {
tempMarkers.push(layer);
layer.remove();
}
});
e.layer.remove();
setRemovedLayers(tempLayers);
setRemovedMarkers(tempMarkers);
return "";
};
The problem is both removedLayers and removedMarkers are empty. I understand it's async so its not instant but it seems no matter how long i wait, its still empty.
Which leads me to think the setState is being executed while the for loop is still running. Adding more hooks seems convoluted, what is the best way to solve this?
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm getting data from a website via a websocket stream, I can see it clearly as a Json object in the console, and now I would like to display it in my frontend but I'm not sure how to do it. I tried assigning the data to a variable but I struggle a little bit to dot so. Is that even the solution ?
my code that fetches the data goes as follow :
const ws = new WebSocket('wss://ws-feed.pro.coinbase.com');
ws.onopen = function () {
ws.send(JSON.stringify({
"type": "subscribe",
"product_ids": [
"BTC-USD",
],
"channels": [
"level2"
]
}));
};
ws.onmessage = function (message) {
const msg = JSON.parse(message.data);
console.log(msg)
}
Even if I manage to display it in my app, it would appear as a whole and I would like to split each key/value pair of the object into different variables to style it properly, how can I do that ?
Thank you very much
you need to store the data inside a variable and update the ui
by changing the innerText field of an html element <div id="app"></div>:
const ws = new WebSocket("wss://ws-feed.pro.coinbase.com");
ws.onopen = function () {
ws.send(
// changed the request a bit because my pc could not handle
// the amount of the messages (1 per 0.1ms)
JSON.stringify({
type: "subscribe",
channels: [{ name: "status" }]
})
);
};
// used for a conditional rendering.
let isFirst = false;
ws.onmessage = function (message) {
/**
* destruct currencies value from the data.
* same as:
* const currencies = message.data.currencies
*/
const { currencies } = JSON.parse(message.data);
/**
* get the name of the first or second object in the currencies array.
*/
if (currencies && currencies.length > 0) {
const index = isFirst ? 0 : 1;
const name = currencies[index].name;
// update is first
isFirst = !isFirst;
/**
* find the html element you want to update.
* update the UI.
*/
document.getElementById("app").innerHTML = `
<h1>First coin on the list is <span>${name}</span></h1>
`;
}
};
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have this request to a firebase database. I would expect it to return all the records in the quotes collection. However, it returns a different set of records (including a different total row count) every time. What do I need to do to “export” all records in a collection consistently?
db.collection("quotes").get()
.then(snapshot => {
console.log(snapshot);
let snapshotArray = [];
snapshot.forEach(doc => {
const data = doc.data();
snapshotArray.push(data);
});
return res.status(200).send(snapshotArray.length)
})
.catch(error => {
console.log(error);
res.status(500).send(error);
});
If you wanna get data of one document you gotta know what its name is. You should check if it does exist as well:
var docRef = db.collection("cities").doc("SF");
docRef.get().then(function(doc) {
if (doc.exists) {
console.log("Document data:", doc.data());
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});
If you want a saved field like ID, you gotta write it this way:
console.log("Document data:", doc.data().id); // only saved ID gets printed
I am trying to edit an already saved note from my notes-app and I think my code isn't correct. I used Firebase as my database and I'm also doing this with ReactJS.
I recently started using ReactJS and I'm trying to improve my coding skills. I have tried some code from other tutorials but still haven't got the desired result.
this.db.ref("notes").on("child_changed", snapshot => {
let note = {
id: snapshot.key,
title: snapshot.val().title,
description: snapshot.val().description
};
const notes = [...this.state.notes];
const index = notes.indexOf(note);
notes[index] = { ...note };
notes[index].title = "";
notes[index].description = "";
this.setState({ notes });
});
I expect that the notes can be edited and saved back in the database.