This question already has answers here:
How to use for in loop and query data from firebase
(2 answers)
Using getDoc().then() inside of a loop Firebase
(2 answers)
How do i use array.push on async loop?
(2 answers)
Fetch in fetch inside a loop JS
(2 answers)
Closed 17 days ago.
I tired with the suggested answer, it is not working in my case.
I am fetching data from a database and storing it in arrays so I can sort the array values later.
But when I check the data from the sorted array in the console it is showing the right output but when I display it on the page it is not.
Basically the array arr stores data of one user and then I find the last element of the array and write 'update' to it.
But it is only showing 'update' to the second user's (last in Db) and writing 'update' to it.
How do I get the right output displayed on the page i.e. showing 'update' to each user's last entry?
(() => {
setTimeout(() => {
let arr = [];
for (let email of userEmails) {
docRef
.where("emailInDb", "==", email)
.get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
let startDate = new Date(doc.data().dateInMills.at(-1) * 1000);
// Adding data to the array
arr.push({
id: doc.id,
email: doc.data().email,
convertedDate: startDate,
});
});
arr.sort((a, b) => {
return a.convertedDate - b.convertedDate;
});
console.log(arr.at(-1)); // This is the correct output shown in console.
dataOnPage.innerHTML = "";
for (let data of arr) {
let detailsOfUsers = `
<div class="flex flex-col justify-center align-middle tableRow">
<span>
<span class='name'>${data.name} </span>
<span class='email block text-[10px] text-gray-400 font-medium'>${
data.email
} </span>
<span class='updateStatus'>${
data === arr.at(-1) ? "udpate" : ""
}
// Here it is only showing update for one record.
</span>
</span>
</div>
`;
dataOnPage.innerHTML += detailsOfUsers;
}
});
}
}, 1000);
})();
Related
This question already has answers here:
Firestore order by two fields
(1 answer)
How can I order a cloud firestore snapshot with 2 fields?
(2 answers)
Closed 1 year ago.
I'm using google Firestore as my database, I wanted to order my material table by two fields (name and date) so I can have it in alphabetical order + in the date it was created, however I got the following error:
This is my code with "acudiente" being the name of the user and "fecha" being the date of the order and "pedidos" being the collection.
useEffect(() => {
const usuariosRef = db.collectionGroup('pedidos')
usuariosRef.orderBy("acudiente", "fecha").onSnapshot(snapshot => {
const tempData = [];
snapshot.forEach((doc) => {
const data = doc.data();
tempData.push(data);
console.log(tempData)
});
setPedidos(tempData);
})
}, []);
This question already has answers here:
Using Javascript loop to create multiple HTML elements
(3 answers)
Closed 2 years ago.
I want to create a new img Element in javascript when my forEach loop read any index of my array and this is the code
axios.get('https://jsonplaceholder.typicode.com/photos', {params: {_limit: 20}}).then(res => {
let values = Object.values(res);
values[0].forEach((item) => {
document.getElementById('root').innerHTML = `<img src="${item.url}">`;
}
})
I thought I would do a runnable version based on Mr Alien's (now deleted) answer. However, as pointed out by Vektor's comment this is likely not helpful (or at least not ideal) if you're working in something like React.
If you are working in something like React you would more likely want to setup state for the images array, render the images based on this array and setup something like a useEffect hook / componentDidMount method to load the images and update the state.
Runnable version based on Mr Alien's (now deleted) answer:
const ele_with_attributes = (tag, attributes = {}) =>
Object.assign(document.createElement(tag), attributes);
const append_image_from_api = (item) =>
document.getElementById('images').appendChild(
ele_with_attributes('img', {
src: item.thumbnailUrl, //item.url,
alt: item.title
})
);
axios
.get('https://jsonplaceholder.typicode.com/photos', {params: {_limit: 5}})
.then(res => res?.data?.forEach(append_image_from_api));
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
<div id="images"></div>
I am trying to order a query by timestamp.
In my document I have a field called "date" which has this form:
date = {
nanoseconds: 963000000,
seconds: 1594917688
}
In my code I have this:
let photosArray = [];
firebase
.getDatabase()
.collection("photos")
.doc(firebase.getCurrentUser().uid)
.collection("userPhotos")
.orderBy("date", "asc") // Sorted by date in ascending direction
.onSnapshot((snapshot) => {
let changes = snapshot.docChanges();
changes.forEach((change) => {
if (change.type === "added") {
// Get the new photo
const photo = change.doc.data();
// Add the photo to the photos list
photosArray.push(photo);
}
});
// The last photo is at the top of the list
setPhotos(photosArray);
But when I render the list of photos, they are unsorted... For example: the first one taken 2 hours ago, the second one taken 1 minute ago, and the last one taken 2 years ago.
UPDATE
This is how I store the date in firestore
Firebase.js:
getTimestamp = () => firebase.firestore.FieldValue.serverTimestamp();
PhotoUploader.js
await firestore
.collection("photos")
.doc(userId)
.collection("userPhotos")
.add({
id,
date: firebase.getTimestamp(),
});
If your date field shows a map with two nested fields, that is not really a timestamp, and it won't sort the way you expect. You should take a look at the code that adds the date field to the document, and make sure it uses a timestamp correctly. Either that, or use a single timestamp numeric value that will sort the way you expect.
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 3 years ago.
Improve this question
I have inputs and a data table. When user fill the inputs and click add button, those new values add to the table. But user can not add same values if the value is already added to the table (same dates and value). Please find the screenshot below.
I have no idea how to do this. I found Set method but it's not working as I expected.
serviceFeeTableData array stores the table data values as objects.
this.state = {
periodFrom: new Date(),
periodTo: new Date(),
serviceFeeType: 'Percentage',
serviceFee: '',
refundableStatus: 'Refundable',
serviceFeeTableData: []
};
Add button function
addNewServiceFee = () => {
let resultData = [...this.state.serviceFeeTableData]
let result = Array.from(new Set(resultData))
return alert('Error! You have already added this value', result)
}
I need to check periodFrom date, periodTo date and serviceFee value is existing in the table record ( in the objecs of serviceFeeTableData ). If user already added that record to table, I need to show a error message. User can't add same exact record again and again. Only one serviceFee can add for the particular time period.
Input field values which is user entered, set to state.
addNewServiceFee function will take the state values and assign them to array as an object. I didn't add the code because of keep the code simple.
You can use the Array includes method if it's not nested object. Eg
var array1 = [1, 2, 3];
console.log(array1.includes(2));
//return true
If its nested object :
function checkObjectExist(obj, list) {
return list.some(elem => elem === obj) //condition to check exist or not
}
Note : You have not clearly mentioned what data you want to check. I am assuming id here. So the code should be like this :
addNewServiceFee = (e) => {
let resultData = [...this.state.serviceFeeTableData]
let checkIsExist = resultData.some(data => data.id === "testingcondition");
if(checkIsExist){
let result = resultData.filter(data => data.id === "testingcondition");
return alert('Error! You have already added this value', result)
}
}
Looping the array and find whether same values are there. If not, add the new record. If yes, notify an error.
let dateFormat = require('dateformat');
for (let a = 0; a < serviceFeeTableData.length; a++) {
let periodFrom = dateFormat(new Date(serviceFeeTableData[a].periodFrom), 'dd-mmm-yyyy')
let periodTo = dateFormat(new Date(serviceFeeTableData[a].periodTo), 'dd-mmm-yyyy')
if (periodFrom === obj1.periodFrom && periodTo === obj1.periodTo) {
statedate = false;
break;
}
}
if (statedate) {
serviceFeeTableData.push(obj1)
} else {
this.notifyError("Selected dates are overlapping with the existing periods. Please select a different period.");
}
}
This question already has answers here:
How to render an array of objects in React?
(6 answers)
Closed 4 years ago.
I am getting the response from an api in this way
data:Array(3)
0:"new"
1:"ruby"
2:"ruby"
I want to display this data under a tr element inside a jsx expression. I made a loop to traverse through the array like this
let course = [];
let userid = this.props.match.params.userid;
axios.get("someapi") //the api to hit request
.then((response) => {
console.log(response);
for (var i = 0; i < response.data.length; i++) {
console.log(response.data[i]);
course.push(response.data[i]);
}
console.log("course", course);
this.setState({ course: course });
console.log("state course", this.state.course);
});
I am getting all the values in both console.log, with "course" and "state course" but can't map it inside tbody to display it in tr tag. I want to render it inside this
<tbody>
<tr>new,ruby and ruby should be displayed here as a list</tr>
</tbody>
What am i doing wrong?
Inside of your table
<tbody>
{this.state.course.map(ele =>
<tr>{ele}</tr>
)}
</tbody>
this should work.
You can also refer to React doc's section: List and Key.
If you want all three courses inside the same <tr> tag as a list you could try:
let course = [];
let userid = this.props.match.params.userid;
axios.get("someapi") //the api to hit request
.then((response) => {
console.log(response);
course = response.data.join(", ");
console.log("course", course);
this.setState({ course: course });
console.log("state course", this.state.course);
});
Then use the course variable in your jsx inside the <tr> tag.
If you want to print one tr for each course set courses equal to response.data and map through it in your jsx