Skip to content
Snippets Groups Projects
Commit d537086f authored by Fionn's avatar Fionn
Browse files

Fixed a saving task bug with permission from lecturer. Task.js post request...

Fixed a saving task bug with permission from lecturer. Task.js post request mainly changed to handle the save without resetting to default form values.
parent 64471501
Branches main
No related tags found
No related merge requests found
Pipeline #20197 failed
...@@ -2,6 +2,7 @@ import './MainPage.css'; ...@@ -2,6 +2,7 @@ import './MainPage.css';
import AddTaskButton from './AddTaskButton'; import AddTaskButton from './AddTaskButton';
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import TaskNote from './Task'; import TaskNote from './Task';
import axios from "axios";
// This is a React component that represents the main page of a to-do application. // This is a React component that represents the main page of a to-do application.
function MainPage() { function MainPage() {
...@@ -16,6 +17,18 @@ function MainPage() { ...@@ -16,6 +17,18 @@ function MainPage() {
const [taskFormCount, setTaskFormCount] = useState(0); const [taskFormCount, setTaskFormCount] = useState(0);
const [fetchedTasks, setFetchedTasks] = useState([]);
useEffect(() => {
axios.get("http://localhost:5000/api/tasks")
.then(res => {
setFetchedTasks(res.data);
})
.catch(error => {
console.error("Could not fetch tasks:", error);
});
}, []);
const handleAddTaskForm = () => { const handleAddTaskForm = () => {
setTaskFormCount(taskFormCount + 1); setTaskFormCount(taskFormCount + 1);
}; };
...@@ -24,7 +37,7 @@ function MainPage() { ...@@ -24,7 +37,7 @@ function MainPage() {
const container = containerRef.current; const container = containerRef.current;
if(!container) return; if(!container) return;
/// Function to handle mouse down event /// Function to handle mouse down event
// It sets the dragging state to true and stores the initial mouse position and scroll position // It sets the dragging state to true and stores the initial mouse position and scroll position
const handleMouseDown = (e) => { const handleMouseDown = (e) => {
if(e.button === 1){ if(e.button === 1){
...@@ -48,7 +61,7 @@ function MainPage() { ...@@ -48,7 +61,7 @@ function MainPage() {
container.scrollTop = scrollPosition.y - dy; container.scrollTop = scrollPosition.y - dy;
} }
} }
// Function to handle mouse up event // Function to handle mouse up event
// It sets the dragging state to false and resets the cursor style // It sets the dragging state to false and resets the cursor style
// It also removes the event listeners for mouse move and mouse up events // It also removes the event listeners for mouse move and mouse up events
...@@ -67,6 +80,7 @@ function MainPage() { ...@@ -67,6 +80,7 @@ function MainPage() {
window.addEventListener('mouseup', handleMouseUp); window.addEventListener('mouseup', handleMouseUp);
return() => { return() => {
// Removing the event listeners when the component is unmounted or when dependencies change // Removing the event listeners when the component is unmounted or when dependencies change
// This prevents memory leaks and ensures that the event listeners are not duplicated // This prevents memory leaks and ensures that the event listeners are not duplicated
container.removeEventListener('mousedown', handleMouseDown); container.removeEventListener('mousedown', handleMouseDown);
...@@ -82,14 +96,13 @@ function MainPage() { ...@@ -82,14 +96,13 @@ function MainPage() {
} }
return ( return (
<div ref={containerRef} style={mainPageDivStyle}> <div ref={containerRef} style={mainPageDivStyle}>
<h1 style={{marginLeft: "30px"}}>TO DO APPLICATION</h1> <h1 style={{marginLeft: "30px"}}>TO DO APPLICATION</h1>
<TaskNote /> <TaskNote fetch={false} initialTasks={fetchedTasks} />
<AddTaskButton onAdd={handleAddTaskForm} /> <AddTaskButton onAdd={handleAddTaskForm} />
{[...Array(taskFormCount)].map((_, index) => ( {[...Array(taskFormCount)].map((_, index) => (
<TaskNote key={index} /> <TaskNote key={`new-task-${index}`} fetch={false} initialTasks={[]} />
))} ))}
</div> </div>
); );
......
...@@ -2,13 +2,16 @@ import React, { useState, useRef, useEffect } from "react"; ...@@ -2,13 +2,16 @@ import React, { useState, useRef, useEffect } from "react";
import './Task.css'; import './Task.css';
import axios from "axios"; import axios from "axios";
export default function TaskNote() { export default function TaskNote({ fetch = false, initialTasks = [] }) {
// State variables for task title, description, completion status, and tasks array // State variables for task title, description, completion status, and tasks array
const [taskTitle, setTaskTitle] = useState('Enter Task Title'); const [taskTitle, setTaskTitle] = useState('Enter Task Title');
const [taskDescription, setTaskDescription] = useState('Enter Task Description'); const [taskDescription, setTaskDescription] = useState('Enter Task Description');
const [taskCompleted, setTaskCompleted] = useState(false); const [taskCompleted, setTaskCompleted] = useState(false);
const [tasks, setTasks] = useState([]); const [tasks, setTasks] = useState([]);
const [showForm, setShowForm] = useState(true)
// Random color generation for task note background // Random color generation for task note background
// The color is generated only once when the component mounts // The color is generated only once when the component mounts
...@@ -35,8 +38,23 @@ export default function TaskNote() { ...@@ -35,8 +38,23 @@ export default function TaskNote() {
// Fetch tasks from the server when the component mounts // Fetch tasks from the server when the component mounts
// The useEffect hook is used to manage side effects in functional components // The useEffect hook is used to manage side effects in functional components
useEffect(() => { useEffect(() => {
fetchTasks(); if (initialTasks.length > 0) {
}, []); setTasks(initialTasks);
setTaskPositions(prevPositions => {
const newPositions = { ...prevPositions };
initialTasks.forEach((task, index) => {
if (!newPositions[task._id]) {
newPositions[task._id] = {
x: 20 + (index * 30),
y: 200 + (index * 30)
};
}
});
return newPositions;
});
}
}, [initialTasks]);
// Update the task positions when the tasks array changes // Update the task positions when the tasks array changes
// This ensures that the task positions are in sync with the tasks fetched from the server // This ensures that the task positions are in sync with the tasks fetched from the server
...@@ -120,13 +138,39 @@ export default function TaskNote() { ...@@ -120,13 +138,39 @@ export default function TaskNote() {
// Send the task data to the server // Send the task data to the server
// The task data is sent to the server using a POST request // The task data is sent to the server using a POST request
axios.post("http://localhost:5000/api/tasks", taskData) axios.post("http://localhost:5000/api/tasks", taskData)
.then(() => { .then((response) => {
setTaskTitle('Enter Task Title');
setTaskDescription('Enter Task Description'); setShowForm(false);
setTaskCompleted(false);
}) // Instead of resetting fields, add the new task to the tasks array
.catch((error) => console.error("Error:" + error)); if (response.data && response.data.message === "Task received") {
}; // Fetch the newly created task to get its ID
axios.get("http://localhost:5000/api/tasks")
.then(res => {
const newTasks = res.data;
// Find the task we just created (should be the one matching our title/description)
const newTask = newTasks.find(task =>
task.title === taskTitle &&
task.description === taskDescription
);
if (newTask) {
// Add the new task to our tasks array
setTasks(prevTasks => [...prevTasks, newTask]);
// Set position for the new task
setTaskPositions(prevPositions => ({
...prevPositions,
[newTask._id]: position
}));
}
})
.catch(error => console.error("Error fetching updated tasks:", error));
}
})
.catch((error) => console.error("Error:" + error));
};
// Handle mouse down event for drag-and-drop functionality // Handle mouse down event for drag-and-drop functionality
// The event is used to determine the starting position of the drag // The event is used to determine the starting position of the drag
...@@ -358,6 +402,7 @@ export default function TaskNote() { ...@@ -358,6 +402,7 @@ export default function TaskNote() {
); );
})} })}
{showForm && (
<form onSubmit={handleSubmit}> <form onSubmit={handleSubmit}>
<div <div
ref={taskRef} ref={taskRef}
...@@ -405,6 +450,7 @@ export default function TaskNote() { ...@@ -405,6 +450,7 @@ export default function TaskNote() {
</div> </div>
</div> </div>
</form> </form>
)}
</> </>
); );
} }
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment