I’ve been facing this issue for a couple of days where I have an array named tempTaskArray, which stores objects filled with data taken from my firestore database.
These objects contain the correct data on each iteration of the .forEach method but when put into my state variable, “tasks” (an array), from array tempTaskArray, all objects contain the data of the last created object.
This issue is not run into when I have an array of strings.
See code below:
const getTasks = () => {
db.collection("users").doc(uid).collection("tasks")
.orderBy("epochdate", "asc")
.get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
// populates array with strings
// tempTaskArray.push(doc.data().taskname)
// tempTaskObject is an empty object
tempTaskObject.taskname= doc.data().taskname
tempTaskObject.duedate= doc.data().duedate
// gets epoch date value and stores it
var epochDate = doc.data().epochdate;
// gets current time
const day = new Date();
let currentTime = day.getTime();
// finds time remaining in epoch
var timeRemaining = epochDate - currentTime;
// finds how many days are left and rounds down
var daysLeft = (timeRemaining / 86400000)
daysLeft = Math.floor(daysLeft)
tempTaskObject.duein = daysLeft
tempTaskArray.push(tempTaskObject)
});
setTasks(tempTaskArray)
})
.catch((error) => {
console.log("Error getting documents: ", error);
});
}
getTasks();
The data taken populating state variable “task” is then rendered in component Task seen below:
<div>
{tasks.map((task) => (
<Task
key={task}
task__title={task.taskname}
due__date={task.duedate}
days__away={task.duein}
/>
))}
</div>
I would be extremely grateful for an explanation of why this is happening. Thanks in advance