|
| 1 | +import { useEffect, useState } from "react"; |
| 2 | +import { deleteTask, getSubtasks } from "../../libs/Datastore/requests"; |
| 3 | +import CircularProgress from "../CircularProgress/circularProgress"; |
| 4 | +import FetchError from "../FetchError/fetchError"; |
| 5 | +import RemoveableListItem from "../RemoveableListItem/removeableListItem"; |
| 6 | +import jotting from "./jotting.module.css"; |
| 7 | + |
| 8 | +/** |
| 9 | + * @param { {id : number } } props The info about the task |
| 10 | + * @param {number} props.id The id of the parent task |
| 11 | + */ |
| 12 | +export default function SubtaskList({ id, subtasksState }) { |
| 13 | + const [subtasks, setSubtasks] = subtasksState; |
| 14 | + |
| 15 | + // componentDidMount() - initally request subtasks |
| 16 | + useEffect(() => { |
| 17 | + (async function () { |
| 18 | + try { |
| 19 | + const initialSubtasks = await getSubtasks(id); |
| 20 | + setSubtasks(initialSubtasks); |
| 21 | + } catch {} |
| 22 | + })(); |
| 23 | + }, []); |
| 24 | + |
| 25 | + const handleRemoveClick = (e) => { |
| 26 | + const itemId = e.target.parentElement.id.substring(2); |
| 27 | + deleteTask(itemId) |
| 28 | + .then(() => { |
| 29 | + for (let i = 0; i < subtasks.length; i++) { |
| 30 | + if (subtasks[i].id == itemId) { |
| 31 | + const newList = subtasks; // Temporarily store list to prevent state mutation |
| 32 | + newList.splice(i, 1); // Remove the element at the current index |
| 33 | + setSubtasks(null); // Needed for state to actually update |
| 34 | + setSubtasks(newList); |
| 35 | + return; |
| 36 | + } |
| 37 | + } |
| 38 | + }) |
| 39 | + .catch(alert); |
| 40 | + }; |
| 41 | + |
| 42 | + if (subtasks instanceof Array) |
| 43 | + return ( |
| 44 | + <ul className={jotting.subtasks}> |
| 45 | + {subtasks.map((item) => ( |
| 46 | + <RemoveableListItem |
| 47 | + key={item.id} |
| 48 | + handleRemoveClick={handleRemoveClick} |
| 49 | + removeText="X" |
| 50 | + id={"s-" + item.id} |
| 51 | + content={item.title} |
| 52 | + /> |
| 53 | + ))} |
| 54 | + </ul> |
| 55 | + ); |
| 56 | + else if (subtasks != null) return <FetchError itemName="subtasks" />; |
| 57 | + else return <CircularProgress />; |
| 58 | +} |
0 commit comments