0

I want to get data from the database. Then change them. And then display. Please tell me how to solve this problem and why I can not do it. Here is my code

let firebaseConfig = {...}; firebase.initializeApp(firebaseConfig); let ref = firebase.database().ref('/data') class DataTable { constructor(parent) { this.parent = parent; } buildTable(data) { this.data = data; const keys = Object.keys(data[0]); console.log(keys) let div = document.createElement('div'); let tab = document.createElement('table'); let tb = document.createElement('tbody'); const buildTableBody = () => { for (let a of data) { let tr = document.createElement('tr'); keys.forEach((key) => { let td = document.createElement('td'); let tn = document.createTextNode(a[key]) td.appendChild(tn); tr.appendChild(td); }); tb.appendChild(tr); } tab.appendChild(tb); div.appendChild(tab); } this.parent.appendChild(div); buildTableBody() } } const table = new DataTable(document.body); table.buildTable( ref.once("value").then((snap) => { const data = snap.val() data.map(i => { let res = { '#': Number(i.id), 'Name': i.name, }; return Object.entries(res).reduce((memo, [key, value]) => { if (value) { return { ...memo, [key]: value } } else { return memo; } }, {}) }) })) 

But it returns to me Promise {}proto: Promise[[PromiseStatus]]: "resolved"[[PromiseValue]]: undefined

1 Answer 1

2

The way you're trying to pass the data into buildTable doesn't work. If you put a breakpoint inside buildTable, you'll be able to see that.

The reason is that the data is loaded from Firebase asynchronously, and any code that needs the data has to be called from inside the once() callback. So you'll want to put the call to buildTable within that callback, like this:

ref.once("value").then((snap) => { const data = snap.val() let result = data.map(i => { let res = { '#': Number(i.id), 'Name': i.name, }; return Object.entries(res).reduce((memo, [key, value]) => { if (value) { return { ...memo, [key]: value } } else { return memo; } }, {}) }) table.buildTable(result); })) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.