I am making a To-Do App. I am using React frontend, Node backend, and Postgresql DB.
I made a component called <TaskLists />
which takes three properties or props:
startDate
endDate
allTasks
allTasks
is an array of task lists. Its basic structure is as follows:
allTasks = [
{
id: //taskList id
list_date: //taskList date
tasks: [
{
id: // task id
title: // task title
done: // boolean value either true or false
}, ...
]
}, ...
]
I am getting this allTasks
array from my backend successfully as I can see from my react dev tool.
Using startDate
and endDate
, I am rendering all the task lists with their list_date
b/w the two using the <TaskLists />
component.
I am trying to render today’s tasks (i.e. 19-07-2024) by the following code:
<TaskLists startDate={props.currentDate} endDate={props.currentDate} currentDate={props.currentDate} allTasks={props.allTasks} />
I made the startDate
and endDate
property same to currentDate
(i.e. 19-07-2024) which I am getting from a parent component.
Now inside my <TaskLists />
component, I want to render either the list of tasks having list_date
b/w startDate
and endDate
or I want to render a <TaskListAbsent />
component which renders if there is no task list b/w startDate
and endDate
.
So I made a useState()
hook:
const [requiredTaskLists, setRequiredTaskLists] = useState([]);
Following is the code to set the variable requiredTaskLists
:
const changeRequiredTaskLists = () => {
let newTaskList = [];
for(let i=0; i<props.allTasks.length; i++) {
if(props.startDate <= props.allTasks[i].list_date && props.endDate >= props.allTask[i].list_date) {
newTaskList.push(allTasks[i]);
}
}
setRequiredTaskLists(newTaskList);
}
And then I called the changeRequiredTaskLists()
function in a useEffect()
hook to call that function with every render:
useEffect(() => {
changeRequiredTaskLists();
}, []);
And lastly, I am rendering the <TaskLists />
component as follows:
return (
<>
{
requiredTaskLists.length !== 0 ?
<>
{
requiredTaskLists.map((taskList) => {
// code for displaying every `taskList` from `requiredTaskLists` array.
})
}
</> :
<>
<TaskListAbsent />
</>
}
</>
)
But the problem is that for
loop inside checkRequiredTaskLists
is not getting executed. And I can confirm that with console logs.
Console logs just before and after for
loop are getting executed and but console logs inside for
loop are not getting executed.
And therefore, the newTaskList
array remains empty []
and requiredTaskLists
gets set to an empty array too []
. Hence, requiredTaskLists.length
always equals to 0
.
And hence my code for displaying list is not rendering at all. It is always the <TaskListAbsent />
component which is rendering.
Please help me with this. Tell me where I am wrong. And is there is another way to achieve what I am trying to achieve?
1