import React, { useState, useEffect } from "react"; import Loader from "../../../components/Loader"; const DisplayTast = ({ farmId }) => { const [tasks, setTasks] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); // Function to delete a task and update the state const handleDeleteTask = async (taskId) => { try { const response = await fetch( `http://localhost:8000/api/v1/task/${taskId}`, { method: "DELETE", credentials: "include", } ); // Assuming that a successful deletion returns a 200 status code if (!response.ok) { throw new Error("Failed to delete task"); } // Optionally check the response, but we'll update state regardless. // Remove the deleted task from state. setTasks((prevTasks) => prevTasks.filter((task) => task._id !== taskId)); console.log(`Task ${taskId} deleted successfully.`); } catch (error) { console.error("Error deleting task:", error); // Optionally, you could set an error state here. } }; useEffect(() => { const fetchTasks = async () => { setLoading(true); setError(null); try { const response = await fetch( `http://localhost:8000/api/v1/task/farm/${farmId}`, { credentials: "include", headers: { "Content-Type": "application/json", }, } ); if (!response.ok) { throw new Error("Failed to fetch tasks"); } const data = await response.json(); setTasks(data); } catch (err) { setError(err.message); } finally { setLoading(false); } }; fetchTasks(); }, [farmId]); if (loading) return
Loading tasks...
; if (error) return
Error: {error}
; if (!tasks || tasks.length === 0) { return
No tasks found for this farm.
; } return (
{tasks.map((task) => ( ))}
Task Type Description Assigned Date Status Action
{task.taskType} {task.description} {new Date(task.assignedDate).toLocaleDateString()} {task.status}
); }; export default DisplayTast;