aboutsummaryrefslogtreecommitdiffstats
path: root/public/projects/react-small-apps/apps/todos/src/views/TodoList/TodoListItem.js
blob: f76c1a10a95b64ee402f0c129023a23202fbe216 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { Link } from "react-router-dom";
import { Button, Input } from "../../components/forms";
import { deleteTodo, toggleTodo } from "../../store/todos/todos.slice";
import { slugify } from "../../utilities/helpers";

function TodoListItem({ todo }) {
  const { id, createdAt, title, done } = todo;
  const [isChecked, setIsChecked] = useState(false);
  const dispatch = useDispatch();

  useEffect(() => {
    if (done) setIsChecked(true);
  }, [done]);

  const handleTodoDone = (checkboxState) => {
    setIsChecked(checkboxState);
    dispatch(toggleTodo(id));
  };

  const todoSlug = slugify(title);

  const classNames = `todos-list__item ${
    isChecked ? "todos-list__item--done" : ""
  }`;

  return (
    <li className={classNames}>
      <span className="todo__date">
        {new Date(createdAt).toLocaleDateString()}
      </span>
      <span className="todo__title">
        <Link to={`/todo/${todoSlug}`} state={{ todoId: todo.id }}>
          {title}
        </Link>
      </span>
      <Input
        type="checkbox"
        label="Done?"
        id={id}
        value={isChecked}
        updateValue={handleTodoDone}
      />
      <Button
        modifiers={["action", "delete"]}
        onClickHandler={() => dispatch(deleteTodo(id))}
      >
        Delete
      </Button>
    </li>
  );
}

export default TodoListItem;