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

add solution #1045

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,4 @@ Implement a simple [TODO app](https://mate-academy.github.io/react_todo-app/) th
- Implement a solution following the [React task guidelines](https://github.com/mate-academy/react_task-guideline#react-tasks-guideline).
- Use the [React TypeScript cheat sheet](https://mate-academy.github.io/fe-program/js/extra/react-typescript).
- Open another terminal and run tests with `npm test` to ensure your solution is correct.
- Replace `<your_account>` with your GitHub username in the [DEMO LINK](https://<your_account>.github.io/react_todo-app/) and add it to the PR description.
- Replace `<your_account>` with your GitHub username in the [DEMO LINK](https://reznik-denis.github.io/react_todo-app/) and add it to the PR description.
172 changes: 27 additions & 145 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,156 +1,38 @@
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import React, { useEffect } from 'react';
import { Header } from './components/Header';
import { Main } from './components/Main';
import { Footer } from './components/Footer';

export const App: React.FC = () => {
return (
<div className="todoapp">
<h1 className="todoapp__title">todos</h1>

<div className="todoapp__content">
<header className="todoapp__header">
{/* this button should have `active` class only if all todos are completed */}
<button
type="button"
className="todoapp__toggle-all active"
data-cy="ToggleAllButton"
/>

{/* Add a todo on form submit */}
<form>
<input
data-cy="NewTodoField"
type="text"
className="todoapp__new-todo"
placeholder="What needs to be done?"
/>
</form>
</header>

<section className="todoapp__main" data-cy="TodoList">
{/* This is a completed todo */}
<div data-cy="Todo" className="todo completed">
<label className="todo__status-label">
<input
data-cy="TodoStatus"
type="checkbox"
className="todo__status"
checked
/>
</label>

<span data-cy="TodoTitle" className="todo__title">
Completed Todo
</span>

{/* Remove button appears only on hover */}
<button type="button" className="todo__remove" data-cy="TodoDelete">
×
</button>
</div>

{/* This todo is an active todo */}
<div data-cy="Todo" className="todo">
<label className="todo__status-label">
<input
data-cy="TodoStatus"
type="checkbox"
className="todo__status"
/>
</label>
import { useDispatch } from './castomHuks/useDispatch';
import { Todo } from './types/Todo';
import { getTodosFromStorage } from './api/todos';
import { useGlobalState } from './castomHuks/useGlobalState';

<span data-cy="TodoTitle" className="todo__title">
Not Completed Todo
</span>

<button type="button" className="todo__remove" data-cy="TodoDelete">
×
</button>
</div>

{/* This todo is being edited */}
<div data-cy="Todo" className="todo">
<label className="todo__status-label">
<input
data-cy="TodoStatus"
type="checkbox"
className="todo__status"
/>
</label>

{/* This form is shown instead of the title and remove button */}
<form>
<input
data-cy="TodoTitleField"
type="text"
className="todo__title-field"
placeholder="Empty todo will be deleted"
value="Todo is being edited now"
/>
</form>
</div>

{/* This todo is in loadind state */}
<div data-cy="Todo" className="todo">
<label className="todo__status-label">
<input
data-cy="TodoStatus"
type="checkbox"
className="todo__status"
/>
</label>

<span data-cy="TodoTitle" className="todo__title">
Todo is being saved now
</span>

<button type="button" className="todo__remove" data-cy="TodoDelete">
×
</button>
</div>
</section>
export const App: React.FC = () => {
const { todos } = useGlobalState();
const dispatch = useDispatch();

{/* Hide the footer if there are no todos */}
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
3 items left
</span>
useEffect(() => {
const todosFromStorage = getTodosFromStorage();

{/* Active link should have the 'selected' class */}
<nav className="filter" data-cy="Filter">
<a
href="#/"
className="filter__link selected"
data-cy="FilterLinkAll"
>
All
</a>
if (todosFromStorage.length > 0) {
dispatch({ type: 'get', payload: todosFromStorage });
} else {
const initial: Todo[] = [];

<a
href="#/active"
className="filter__link"
data-cy="FilterLinkActive"
>
Active
</a>
localStorage.setItem('todos', JSON.stringify(initial));
}
}, []);

Check warning on line 26 in src/App.tsx

View workflow job for this annotation

GitHub Actions / run_linter (14.x)

React Hook useEffect has a missing dependency: 'dispatch'. Either include it or remove the dependency array

<a
href="#/completed"
className="filter__link"
data-cy="FilterLinkCompleted"
>
Completed
</a>
</nav>
return (
<div className="todoapp">
<h1 className="todoapp__title">todos</h1>

{/* this button should be disabled if there are no completed todos */}
<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
>
Clear completed
</button>
</footer>
<div className="todoapp__content">
<Header />
<Main />
{todos.length > 0 && <Footer />}
</div>
</div>
);
Expand Down
37 changes: 37 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Todo } from '../types/Todo';

export const getTodosFromStorage = () => {
const storedItems = localStorage.getItem('todos');

if (storedItems) {
return JSON.parse(storedItems);
}

return [];
};

export const addTodoToStorage = (todo: Todo) => {
const todos = getTodosFromStorage();

localStorage.setItem('todos', JSON.stringify([...todos, todo]));
};

export const deleteTodoFromStorage = (id: number) => {
const todos = getTodosFromStorage();
const newTodos = todos.filter((todo: Todo) => todo.id !== id);

localStorage.setItem('todos', JSON.stringify(newTodos));
};

export const patchTodoFromStorage = (id: number, data: Omit<Todo, 'id'>) => {
const todos = getTodosFromStorage();
const newTodos = todos.map((todo: Todo) => {
if (todo.id === id) {
return { ...todo, ...data };
} else {
return todo;
}
});

localStorage.setItem('todos', JSON.stringify(newTodos));
};
4 changes: 4 additions & 0 deletions src/castomHuks/useDispatch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import React from 'react';
import { DispatchContext } from '../context/GlobalProvider';

export const useDispatch = () => React.useContext(DispatchContext);
4 changes: 4 additions & 0 deletions src/castomHuks/useGlobalState.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import React from 'react';
import { StateContext } from '../context/GlobalProvider';

export const useGlobalState = () => React.useContext(StateContext);
66 changes: 66 additions & 0 deletions src/components/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import React, { useState } from 'react';
import { useGlobalState } from '../castomHuks/useGlobalState';
import { Actions } from '../types/Actions';
import classNames from 'classnames';
import { useDispatch } from '../castomHuks/useDispatch';
import { filteredTodos } from '../utils/filteredTodos';
import { FooterButton } from './FooterButton';
import { SelectedState } from '../types/SelectedState';

export const Footer: React.FC = () => {
const [selected, setSelected] = useState<SelectedState>({
all: true,
active: false,
completed: false,
});
const { todos } = useGlobalState();
const dispatch = useDispatch();

const handleSelected = (action: Actions) => {
setSelected(prevState => {
const newState = { ...prevState };

for (const key in newState) {
if (key !== action) {
newState[key as keyof SelectedState] = false;
} else {
newState[key as keyof SelectedState] = true;
}
}

return newState;
});
dispatch({ type: 'setActions', payload: action });
};

return (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{`${filteredTodos(todos, Actions.ACTIVE).length} items left`}
</span>

<nav className="filter" data-cy="Filter">
{Object.values(Actions).map((action, index) => {
const upperAction =
action.slice(0, 1).toUpperCase() + action.slice(1);

return (
<a
href="#/"
className={classNames('filter__link', {
selected: selected[action],
})}
data-cy={`FilterLink${upperAction}`}
key={index}
onClick={() => handleSelected(action)}
>
{upperAction}
</a>
);
})}
</nav>

<FooterButton />
</footer>
);
};
42 changes: 42 additions & 0 deletions src/components/FooterButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import React from 'react';
import { useGlobalState } from '../castomHuks/useGlobalState';
import { deleteTodoFromStorage } from '../api/todos';
import { useDispatch } from '../castomHuks/useDispatch';

export const FooterButton: React.FC = () => {
const { todos, inputHeaderRef } = useGlobalState();
const dispatch = useDispatch();

const clearCompleted = async () => {
const completedTodos = todos.filter(todo => todo.completed);

const deletePromises = completedTodos.map(
todo =>
new Promise<void>(resolve => {
deleteTodoFromStorage(todo.id);
dispatch({ type: 'deleteTodo', payload: todo.id });
resolve();
}),
);

if (inputHeaderRef?.current) {
inputHeaderRef.current.focus();
}

await Promise.allSettled(deletePromises);
};

const hasCompletedTodos = todos.some(todo => todo.completed);

return (
<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
disabled={!hasCompletedTodos}
onClick={clearCompleted}
>
Clear completed
</button>
);
};
Loading
Loading