|
| 1 | +import styledCheckbox from "./styledCheckbox.module.css"; |
| 2 | +import { useEffect, useRef, useState } from "react"; |
| 3 | +import { updateTaskStatus } from "../../libs/Datastore/requests"; |
| 4 | + |
| 5 | +/** |
| 6 | + * @param {object} props |
| 7 | + * @param {number} props.id |
| 8 | + * @param {string} props.prefix |
| 9 | + * @param {boolean} props.completed |
| 10 | + */ |
| 11 | +export default function StyledCheckbox({ id, prefix, completed }) { |
| 12 | + const [checked, setChecked] = useState(completed); |
| 13 | + const ref = useRef(null); |
| 14 | + |
| 15 | + /** |
| 16 | + * Event handler for when the checkbox is checked or unchecked |
| 17 | + * @description Uses whether the label's background position contains a negative sign |
| 18 | + * to determine whether the checkbox is currently checked |
| 19 | + * Instantaneously updates UI but undoes checkbox and alerts if there is a fetch error, |
| 20 | + * using Promise.race() |
| 21 | + * @param {Event} e |
| 22 | + */ |
| 23 | + const handleCheckboxChange = (e) => { |
| 24 | + const newCheckboxValue = !checked; |
| 25 | + Promise.race([ |
| 26 | + updateTaskStatus(id, newCheckboxValue).catch((err) => { |
| 27 | + setChecked(!newCheckboxValue); |
| 28 | + alert(err); |
| 29 | + }), |
| 30 | + setChecked(newCheckboxValue), |
| 31 | + ]); |
| 32 | + }; |
| 33 | + |
| 34 | + useEffect(() => { |
| 35 | + ref.current.style.backgroundPosition = checked |
| 36 | + ? "0px -20px" |
| 37 | + : "0px 0px"; |
| 38 | + }, [checked]); |
| 39 | + |
| 40 | + return ( |
| 41 | + <React.Fragment> |
| 42 | + <input |
| 43 | + id={`${prefix}${id}`} |
| 44 | + className={styledCheckbox.taskCompletionCheckbox} |
| 45 | + type="checkbox" |
| 46 | + checked={checked} |
| 47 | + onChange={handleCheckboxChange} |
| 48 | + /> |
| 49 | + <label |
| 50 | + ref={ref} |
| 51 | + htmlFor={`${prefix}${id}`} |
| 52 | + className={styledCheckbox.taskCompletionCheckbox} |
| 53 | + title="Mark as complete" |
| 54 | + ></label> |
| 55 | + </React.Fragment> |
| 56 | + ); |
| 57 | +} |
0 commit comments