I'm having trouble fetching data from realtime database. Everytime I insert a new data it duplicates the whole table. please help.
here is my output:
here is my code:
function fetchData() {
var tbody;
const dbRef = query(
ref(database, "vote/"),
orderByChild("department"),
equalTo(getUrlParameter("department"))
);
onValue(dbRef, (snapshot) => {
const data = snapshot.val();
snapshot.forEach((childSnapshot) => {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
tbody += `<tr>
<td>${childData.judgeName}</td>
<td>${childData.score1}</td>
<td>${childData.score2}</td>
<td>${childData.score3}</td>
<td>${childData.score4}</td>
<td>${childData.score5}</td>
</tr>`;
});
$(".list").html(tbody);
});
}
fetchData();
I tried pushing it inside of array but nothing change its still duplicating the whole data/table
try this
function fetchData() {
const dbRef = query(
ref(database, "vote/"),
orderByChild("department"),
equalTo(getUrlParameter("department"))
);
onValue(dbRef, (snapshot) => {
const data = snapshot.val();
let tbody = ''
snapshot.forEach((childSnapshot) => {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
tbody += `<tr>
<td>${childData.judgeName}</td>
<td>${childData.score1}</td>
<td>${childData.score2}</td>
<td>${childData.score3}</td>
<td>${childData.score4}</td>
<td>${childData.score5}</td>
</tr>`;
});
$(".list").html(tbody);
});
}
Related
I have these two functions that take data from a google sheet and then send a whatsapp message. I can't modify the first function (getSheetData_) to take only the data from the last row. I only have two columns (name and phone). I have a trigger that launches the script on every change.
source: https://www.labnol.org/whatsapp-api-google-sheets-220520
const getSheetData_ = () => {
const [header, ...rows] = SpreadsheetApp.getActiveSheet().getDataRange().getDisplayValues();
const data = [];
rows.forEach((row) => {
const recipient = { };
header.forEach((title, column) => {
recipient[title] = row[column];
});
data.push(recipient);
});
return data;
};
const main = () => {
const data = getSheetData_();
data.forEach((recipient) => {
const status = sendMessage_({
recipient_number: recipient["Phone Number"].replace(/[^\d]/g, ""),
customer_name: recipient["Customer Name"]
});
});
};
Solution:
const getSheetData_ = () => {
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = sheet.getRange(sheet.getLastRow(),1,1,2);
const header = ['Customer Name', 'Phone Number'];
const rows = lastRow.getDisplayValues();
const data = [];
rows.forEach((row) => {
const recipient = { };
header.forEach((title, column) => {
recipient[title] = row[column];
});
data.push(recipient);
});
return data;
};
const getSearch = async function () {
try {
const res = await fetch(
`http://dataservice.accuweather.com/locations/v1/cities/search?apikey=${apiKey}&q=${inputValue}`
);
const data = await res.json();
// console.log(data);
const dataArr = Object.entries(data);
dataArr.forEach(([key, value]) => {
const city = value.AdministrativeArea.LocalizedName;
const country = value.Country.LocalizedName;
const countryCode = value.Country.ID;
const markup = `
<li class="search-result search-result--${key}">${city}, ${country}, ${countryCode}</li>
`;
console.log(markup);
});
ul.innerHTML = '';
ul.insertAdjacentHTML('afterbegin', markup);
} catch (err) {
console.error(err);
}
};
I am trying to add all li's to my ul. When I console.log(markup), the results come back separately, but when I insertAdjacentHTML() only the last li is displayed.
This is for search results, so the amount of li's is unknown for each search input, and I want the li's to match the number of results.
I'm surprised that it even worked once:
const getSearch = async function () {
try {
const res = await fetch(
`http://dataservice.accuweather.com/locations/v1/cities/search?apikey=${apiKey}&q=${inputValue}`
);
const data = await res.json();
// console.log(data);
const dataArr = Object.entries(data);
dataArr.forEach(([key, value]) => {
const city = value.AdministrativeArea.LocalizedName;
const country = value.Country.LocalizedName;
const countryCode = value.Country.ID;
const markup = `
<li class="search-result search-result--${key}">${city}, ${country}, ${countryCode}</li>
`;
console.log(markup);
// try this
ul.insertAdjacentHTML('afterbegin', markup);
});
} catch (err) {
console.error(err);
}
};
I would rather use createElement than innerHTML
I'm unable to get an error response for the web app, it displays if there's a valid response but doesn't display anything on a bad request. How can I get the error message either on the console or as json string
Here's the code below
const getWeather = () => {
let city = document.querySelector("input").value;
fetch(
`http://api.weatherapi.com/v1/current.json?key=ca7ec552bc034514a9792135211812&q=${city}&aqi=no`
)
.then((data) => data.json())
.then((data) => displayWeather(data));
};
document.querySelector("button").addEventListener("click", () => {
getWeather();
document.querySelector("input").innerText = "";
});
const displayWeather = (data) => {
const localInfo = data.location.localtime;
const name = data.location.name;
const icon = data.current.condition.icon;
const text = data.current.condition.text;
const temp = data.current.temp_c;
const humidity = data.current.humidity;
const country = data.location.country;
const windSpeed = data.current.wind_kph;
const code = data.current.condition.code;
const error =data.error.message;
console.log(name, icon, text, temp, humidity, country, windSpeed, code, error);
Live code at this time of writing this: https://github.com/samuelajala01/my-weather-app/blob/master/script.js
The weather API will only send error sub object if there is error, otherwise it will just send current and location sub objects, hence you just had to add a check for existence of error object in response data
Something like this :
document.querySelector("button").addEventListener("click", () => {
getWeather();
document.querySelector("input").innerHTML = " ";
});
const displayWeather = (data) => {
if (data.error) {
alert(data.error.message);
} else {
const localInfo = data.location.localtime;
const name = data.location.name;
const icon = data.current.condition.icon;
const text = data.current.condition.text;
const temp = data.current.temp_c;
const humidity = data.current.humidity;
const country = data.location.country;
const windSpeed = data.current.wind_kph;
const code = data.current.condition.code;
console.log(name, icon, text, temp, humidity, country, windSpeed, code);
}
}
const getWeather = () => {
let city = document.querySelector("input").value;
fetch(
`http://api.weatherapi.com/v1/current.json?key=ca7ec552bc034514a9792135211812&q=${city}&aqi=no`
)
.then((data) => data.json())
.then((data) => displayWeather(data))
};
var emp = db.collection('BookedTicketData').get().then((snapshot) => {
snapshot.docs.forEach((doc) => {
data = doc.data();
bseat = data.AllSeat
// console.log(bseat)
allseat.concat(bseat)
})
console.log(allseat)
return allseat;
}).then((alls) => {
console.log(alls)
})
I have done this code to get the array from the doucumnets of firebase and it is coming seperatly i want to combine all the array in single array and print the array in console.log(alls)
1-> [4,46,324,346,345,234,3446,36]
2-> [324,6,3,44,6,2,6,35,2,7,23]
alls -> [4,46,324,346,345,234,3446,36,3244,6,3,44,6,2,6,35,2,7,23]
If I correctly understand your question, the following should do the trick:
var emp = db
.collection('BookedTicketData')
.get()
.then((snapshot) => {
let allseat = [];
snapshot.docs.forEach((doc) => {
data = doc.data();
bseat = data.AllSeat;
// console.log(bseat)
allseat = allseat.concat(bseat);
});
console.log(allseat);
return allseat;
})
Path 1 - Match_Creator/cricket/matchList;
Path 2 - Match_Creator/cricket/completedMatchList;
I have a collection called matchList (Path 1) In which i am having a doc called c434108.
Now I want to move this doc(c434108) to Path 2;
/* eslint-disable promise/catch-or-return */
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const { db } = require("./db/index");
const createCompletedMatchListDoc = (request, response) => {
completedMatchDocsData();
};
function completedMatchDocsData() {
createNewCompletedMatchDocs()
}
function getOldCompletedMatchDocs(){
var completedMatchesRef = db
.collection("Match_Creator")
.doc("cricket")
.collection("matchList");
var completedMatchDocData;
var completedMatchDataArr = [];
return new Promise(resolve => {
let query = completedMatchesRef
.where("status", "==", "live")
.get()
.then(snapshot => {
// eslint-disable-next-line promise/always-return
if (snapshot.empty) {
console.log("No matching documents.");
return;
}
snapshot.forEach(doc => {
completedMatchDocData = doc.data();
completedMatchDataArr.push(completedMatchDocData);
resolve(completedMatchDataArr);
});
console.log("sarang", completedMatchDataArr[2]);
})
.catch(err => {
console.log("Error getting documents", err);
});
});
}
const createNewCompletedMatchDocs = (async(change, context) => {
let completedMatchData = await getOldCompletedMatchDocs();
console.log('aman', completedMatchData[1]);
const newValue = change.after.data();
const previousValue = change.before.data();
const st1 =newValue.status;
const st2 = previousValue.status;
console.log('I am a log entry' + st1 + ' ' + st2);
var data = completedMatchData[0];
return db.collection('Match_Creator').doc('cricket').collection('completedMatchList').add(data)
.catch(error => {
console.log('Error writting document: ' + error);
return false;
});
})
module.exports = createCompletedMatchListDoc;
And After copy this doc(c434108) i want to delete this doc(c434108) from path 1.
And My index.js file is:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const storeMatchData = require("./liveScoring");
const createCompletedMatchListDoc = require("./completedMatchList");
var http = require("https");
module.exports = {
liveScoring: functions.https.onRequest(storeMatchData),
createCompletedMatchListDoc: functions.https.onRequest(
createCompletedMatchListDoc
)
};
I am able to solve my problem.
This is my completeMatchList.js file
/* eslint-disable promise/catch-or-return */
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const { db } = require("./db/index");
const createCompletedMatchListDoc = (request, response) => {
completedMatchDocsData();
};
function completedMatchDocsData() {
setNewCompletedMatchDocs()
}
function getOldCompletedMatchDocs(){
var completedMatchesRef = db
.collection("Match_Creator")
.doc("cricket")
.collection("matchList");
var completedMatchDocData;
var completedMatchDataArr = [];
return new Promise(resolve => {
let query = completedMatchesRef
.where("status", "==", "live")
.get()
.then(snapshot => {
// eslint-disable-next-line promise/always-return
if (snapshot.empty) {
console.log("No matching documents.");
return;
}
snapshot.forEach(doc => {
// completedMatchDocData = doc.data();
completedMatchDocData = {
docId: "",
docData: ""
}
completedMatchDocData.docId = doc.id;
completedMatchDocData.docData = doc.data();
completedMatchDataArr.push(completedMatchDocData);
resolve(completedMatchDataArr); // Here i am getting the data and pushing it in array
});
console.log("sarang", completedMatchDataArr);
})
.catch(err => {
console.log("Error getting documents", err);
});
});
}
const setNewCompletedMatchDocs = (async () => {
let getCompletedMatchData = await getOldCompletedMatchDocs();
// console.log("balram", getCompletedMatchData[0].docId);
let newCompletedMatchDocRef = db.collection("Match_Creator").doc("cricket").collection("completedMatchList").doc(getCompletedMatchData[0].docId);
return newCompletedMatchDocRef.set(getCompletedMatchData[0].docData); //set/copy the data to new path.
})
This is my main index.js file
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const storeMatchData = require("./liveScoring");
const createCompletedMatchListDoc = require("./completedMatchList");
const { db } = require("./db/index");
var http = require("https");
module.exports = {
liveScoring: functions.https.onRequest(storeMatchData),
createCompletedMatchListDoc: functions.https.onRequest(
createCompletedMatchListDoc
)
};
Now after copy document data to a new path i will delete the previous document. For deleting the document i have not written the function.
I'm not seeing anything that would allow you to move a document between collections(someone correct me if I'm wrong). You have to copy from the old collection to the new one and then remove the old one.
This is another post on StackOverflow that is running into this same issue and someone provided Java code on how to implement it.
EDIT: Updated link.
Hope this helps.