Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

day3 「Todoの削除機能の実装」の一例(論理削除パターン) #5

Merged
merged 1 commit into from Jul 27, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 5 additions & 3 deletions src/features/todos/components/TodoList.tsx
@@ -1,8 +1,10 @@
import type { FC } from 'react';
import { useAppSelector } from '../../../app/hooks';
import { useAppSelector, useAppDispatch } from '../../../app/hooks';
import { remove, selectTodos } from '../todosSlice';

export const TodoList: FC = () => {
const todos = useAppSelector((state) => state.todos.todos);
const todos = useAppSelector(selectTodos);
const dispatch = useAppDispatch();

return (
<>
Expand Down Expand Up @@ -50,7 +52,7 @@ export const TodoList: FC = () => {
<td>
<button
onClick={() => {
//TODO: 削除機能の実装
dispatch(remove(todo.id));
}}
>
削除
Expand Down
2 changes: 2 additions & 0 deletions src/features/todos/crud/index.ts
@@ -0,0 +1,2 @@
export { createTodo } from './create';
export { removeTodo } from './remove';
21 changes: 21 additions & 0 deletions src/features/todos/crud/remove.ts
@@ -0,0 +1,21 @@
import type { Todo } from '../types';
import { getCurrentDateTime } from '../utils/date';

export const removeTodo = ({
id,
title,
body,
status,
createdAt,
updatedAt,
}: Todo): Todo => {
return {
id,
title,
body,
status,
createdAt,
updatedAt,
deletedAt: getCurrentDateTime(),
};
};
18 changes: 15 additions & 3 deletions src/features/todos/todosSlice.ts
@@ -1,7 +1,8 @@
import { createSlice } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';
import type { TodoInput, Todo } from './types';
import { createTodo } from './crud/create';
import type { RootState } from '../../app/store';
import type { TodoInput, Todo, TodoId } from './types';
import { createTodo, removeTodo } from './crud';

export type TodoState = {
todos: Todo[];
Expand All @@ -23,9 +24,20 @@ export const todoSlice = createSlice({
const todo = createTodo(action.payload);
state.todos.push(todo);
},
remove: (state, action: PayloadAction<TodoId>) => {
const id = action.payload;
const index = state.todos.findIndex((todo) => todo.id === id);
const todo = state.todos[index];
if (!todo) return;

state.todos[index] = removeTodo(todo);
},
},
});

export const { create } = todoSlice.actions;
export const { create, remove } = todoSlice.actions;

export const selectTodos = (state: RootState) =>
state.todos.todos.filter((todo) => todo.deletedAt === undefined);

export default todoSlice.reducer;