Skip to content

Commit

Permalink
refactor: extract variables from toggleMultipleTodosStatus in TodoCon…
Browse files Browse the repository at this point in the history
…text
  • Loading branch information
przwojwwp committed Oct 8, 2024
1 parent 1b0db7d commit 407a123
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 10 deletions.
2 changes: 2 additions & 0 deletions src/components/Todos/Todos.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export const Todos = () => {
const [editingTodoId, setEditingTodoId] = useState<number | null>(null);
const [editingTitle, setEditingTitle] = useState('');
const renameInputRef = useRef<HTMLInputElement | null>(null);
const checkboxRef = useRef<HTMLInputElement | null>(null);
const { toggleTodoStatus, updateTodoTitle, deleteTodo, filteredTodos } =
useTodoContext();

Expand Down Expand Up @@ -70,6 +71,7 @@ export const Todos = () => {
{/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}
<label className="todo__status-label">
<input
ref={checkboxRef}
data-cy="TodoStatus"
type="checkbox"
className="todo__status"
Expand Down
23 changes: 13 additions & 10 deletions src/components/context/TodoContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
Expand Down Expand Up @@ -47,6 +48,16 @@ export const TodoProvider = ({ children }: TodoProviderProps) => {
const [filter, setFilter] = useState<Filter>('All');
const headerInputRef = useRef<HTMLInputElement>(null);

const areAllCompleted = useMemo(() => {
return todos.every(todo => todo.completed);
}, [todos]);

const updatedTodos = useMemo(() => {
return todos.map(todo => {
return { ...todo, completed: !areAllCompleted };
});
}, [areAllCompleted, todos]);

useEffect(() => {
localStorage.setItem('todos', JSON.stringify(todos));

Expand Down Expand Up @@ -86,16 +97,8 @@ export const TodoProvider = ({ children }: TodoProviderProps) => {
}, []);

const toggleMultipleTodosStatus = useCallback(() => {
setTodos(prevTodos => {
const areAllCompleted = prevTodos.every(todo => todo.completed);

const updatedTodos = prevTodos.map(todo => {
return { ...todo, completed: !areAllCompleted };
});

return updatedTodos;
});
}, []);
setTodos(updatedTodos);
}, [updatedTodos]);

const updateTodoTitle = useCallback((id: number, newTitle: string) => {
setTodos(prevTodos =>
Expand Down

0 comments on commit 407a123

Please sign in to comment.