From 9ccb572a22da837d73b9b53ce63612ca6fad72b2 Mon Sep 17 00:00:00 2001 From: Aidan Shaw Date: Sat, 23 Apr 2022 09:59:38 +0000 Subject: [PATCH] Added feature to check, uncheck and reset todos items --- app/controllers/home_controller.rb | 7 +++++-- app/javascript/components/TodoList/index.tsx | 20 +++++++++++++++++--- config/routes.rb | 2 +- 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/app/controllers/home_controller.rb b/app/controllers/home_controller.rb index 064809b..cc43861 100644 --- a/app/controllers/home_controller.rb +++ b/app/controllers/home_controller.rb @@ -9,19 +9,22 @@ def landing def edit_todo_item @todo_item.update(todo_item_params) + render json: @todo_item end def reset_todo_items Todo.update_all(checked: false) + @todos = Todo.all.order(:id) + render json: @todos end private def todo_item_params - params.permit(:id, :title, :checked) + params.require(:home).permit(:id, :title, :checked) end def set_todo_item - @todo_item = Todo.find(todo_item_params[:id]) + @todo_item = Todo.find(params[:id]) end end diff --git a/app/javascript/components/TodoList/index.tsx b/app/javascript/components/TodoList/index.tsx index 60f7fd3..5639788 100644 --- a/app/javascript/components/TodoList/index.tsx +++ b/app/javascript/components/TodoList/index.tsx @@ -1,4 +1,4 @@ -import React, { useEffect } from "react"; +import React, { useState, useEffect } from "react"; import { Container, ListGroup, Form } from "react-bootstrap"; import { ResetButton } from "./uiComponent"; import axios from "axios"; @@ -14,6 +14,7 @@ type Props = { }; const TodoList: React.FC = ({ todoItems }) => { + const [todoList, setTodoList] = useState([...todoItems]); useEffect(() => { const token = document.querySelector( "[name=csrf-token]" @@ -25,21 +26,34 @@ const TodoList: React.FC = ({ todoItems }) => { e: React.ChangeEvent, todoItemId: number ): void => { + const checked = e.target.checked; axios.post("/todo", { id: todoItemId, checked: e.target.checked, + }).then(() => { + setTodoList(prevList => { + const updatedList = prevList.map(todo => { + if (todo.id === todoItemId) { + todo.checked = checked; + } + return todo; + }) + return updatedList; + }); }); }; const resetButtonOnClick = (): void => { - axios.post("/reset").then(() => location.reload()); + axios.post("/reset").then(response => { + setTodoList(response.data); + }); }; return (

2022 Wish List

- {todoItems.map((todo) => ( + {todoList.map((todo) => (