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 temp solution #1521

Open
wants to merge 7 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
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ and implement the ability to toggle and rename todos.
## Toggling a todo status

Toggle the `completed` status on `TodoStatus` change:

- Install Prettier Extention and use this [VSCode settings](https://mate-academy.github.io/fe-program/tools/vscode/settings.json) to enable format on save.
- covered the todo with a loader overlay while waiting for API response;
- the status should be changed on success;
Expand Down Expand Up @@ -38,6 +39,7 @@ Implement the ability to edit a todo title on double click:
- or the deletion error message if we tried to delete the todo.

## If you want to enable tests

- open `cypress/integration/page.spec.js`
- replace `describe.skip` with `describe` for the root `describe`

Expand All @@ -47,4 +49,4 @@ Implement the ability to edit a todo title on double click:

- Implement a solution following the [React task guideline](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).
- Replace `<your_account>` with your Github username in the [DEMO LINK](https://<your_account>.github.io/react_todo-app-with-api/) and add it to the PR description.
- Replace `<your_account>` with your Github username in the [DEMO LINK](https://IrbisKronos.github.io/react_todo-app-with-api/) and add it to the PR description.
209 changes: 190 additions & 19 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,197 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import { UserWarning } from './UserWarning';
import React, { useEffect, useMemo, useState } from 'react';

const USER_ID = 0;
import { Todo } from './types/Todo';
import { FilterCriteria } from './types/FilterCriteria';
import * as todoServise from './api/todos';
import { Header, Footer, TodoList, ErrorNotification } from './components';

const filterTodos = (tasks: Todo[], filterCriteria: FilterCriteria) => {
return tasks.filter(task => {
const matchesStatus =
filterCriteria === FilterCriteria.All ||
(filterCriteria === FilterCriteria.Active && !task.completed) ||
(filterCriteria === FilterCriteria.Completed && task.completed);

return matchesStatus;
});
};

export const App: React.FC = () => {
if (!USER_ID) {
return <UserWarning />;
}
const [todos, setTodos] = useState<Todo[]>([]);
const [errorMessage, setErrorMessage] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [filter, setFilter] = useState<FilterCriteria>(FilterCriteria.All);
const [titleTodo, setTitleTodo] = useState('');
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [loadingTodoIds, setLoadingTodoIds] = useState<number[]>([]);
const [isEditingTodos, setIsEditingTodos] = useState(false);

useEffect(() => {
setIsLoading(true);

todoServise
.getTodos()
.then(setTodos)
.catch(() => {
setErrorMessage('Unable to load todos');
})
.finally(() => {
setIsLoading(false);
});
}, []);

useEffect(() => {
if (errorMessage) {
const timer = setTimeout(() => {
setErrorMessage('');
}, 3000);

return () => clearTimeout(timer);
}
}, [errorMessage]);

const getFilteredTodos = useMemo(() => {
return filterTodos(todos, filter);
}, [todos, filter]);

const addTodo = ({ title, userId, completed }: Todo) => {
setIsLoading(true);

const newTempTodo = {
id: 0,
userId: todoServise.USER_ID,
title,
completed: false,
};

setTempTodo(newTempTodo);

todoServise
.createTodo({ title, userId, completed })
.then(newTodo => {
setTodos(currentTodos => [...currentTodos, newTodo]);
setTitleTodo('');
})
.catch(() => {
setErrorMessage('Unable to add a todo');
})
.finally(() => {
setIsLoading(false);
setTempTodo(null);
});
};

const updateTodo = (updatedTodo: Todo) => {
setLoadingTodoIds(ids => [...ids, updatedTodo.id]);

todoServise
.updateTodo(updatedTodo)
.then(todo => {
setTodos(currentTodos => {
const newTodo = [...currentTodos];
const index = newTodo.findIndex(post => post.id === updatedTodo.id);

newTodo.splice(index, 1, todo);

return newTodo;
});

setIsEditingTodos(true);
})
.catch(() => {
setErrorMessage('Unable to update a todo');
})
.finally(() => {
setLoadingTodoIds(ids => ids.filter(id => id !== updatedTodo.id));
setTitleTodo('');
setIsEditingTodos(false);
});
};

const deleteTodo = (todoId: number) => {
setLoadingTodoIds(ids => [...ids, todoId]);

todoServise
.deleteTodo(todoId)
.then(() => {
setTodos(currentTodos =>
currentTodos.filter(todo => todo.id !== todoId),
);
})
.catch(() => {
setErrorMessage('Unable to delete a todo');
})
.finally(() => {
setLoadingTodoIds(ids => ids.filter(id => id !== todoId));
});
};

const handleFilter = (filterType: FilterCriteria) => {
setFilter(filterType);
};

const activeTodos = todos.filter(todo => !todo.completed).length || 0;

const completedTodos = todos.filter(todo => todo.completed).length || 0;

const toggleAllTodos = () => {
const hasIncomplete = todos.some(todo => !todo.completed);

const toggledTodos = hasIncomplete
? todos
.filter(todo => !todo.completed)

Check failure on line 142 in src/App.tsx

View workflow job for this annotation

GitHub Actions / run_linter (20.x)

Expected indentation of 8 spaces but found 10
.map(todo => ({

Check failure on line 143 in src/App.tsx

View workflow job for this annotation

GitHub Actions / run_linter (20.x)

Expected indentation of 8 spaces but found 10
...todo,

Check failure on line 144 in src/App.tsx

View workflow job for this annotation

GitHub Actions / run_linter (20.x)

Expected indentation of 10 spaces but found 12
completed: true,

Check failure on line 145 in src/App.tsx

View workflow job for this annotation

GitHub Actions / run_linter (20.x)

Expected indentation of 10 spaces but found 12
}))

Check failure on line 146 in src/App.tsx

View workflow job for this annotation

GitHub Actions / run_linter (20.x)

Expected indentation of 8 spaces but found 10
: todos.map(todo => ({
...todo,

Check failure on line 148 in src/App.tsx

View workflow job for this annotation

GitHub Actions / run_linter (20.x)

Expected indentation of 8 spaces but found 10
completed: false,

Check failure on line 149 in src/App.tsx

View workflow job for this annotation

GitHub Actions / run_linter (20.x)

Expected indentation of 8 spaces but found 10
}));

Check failure on line 150 in src/App.tsx

View workflow job for this annotation

GitHub Actions / run_linter (20.x)

Expected indentation of 6 spaces but found 8

toggledTodos.forEach(updateTodo);
};

return (
<section className="section container">
<p className="title is-4">
Copy all you need from the prev task:
<br />
<a href="https://github.com/mate-academy/react_todo-app-add-and-delete#react-todo-app-add-and-delete">
React Todo App - Add and Delete
</a>
</p>

<p className="subtitle">Styles are already copied</p>
</section>
<div className="todoapp">
<h1 className="todoapp__title">todos</h1>

<div className="todoapp__content">
<Header
todos={todos}
addTodo={addTodo}
setErrorMessage={setErrorMessage}
isLoading={isLoading}
titleTodo={titleTodo}
setTitleTodo={setTitleTodo}
toggleAllTodos={toggleAllTodos}
activeTodos={activeTodos}
/>

<TodoList
todos={getFilteredTodos}
deleteTodo={deleteTodo}
tempTodo={tempTodo}
isEditingTodos={isEditingTodos}
setErrorMessage={setErrorMessage}
loadingTodoIds={loadingTodoIds}
setLoadingTodoIds={setLoadingTodoIds}
setTodos={setTodos}
/>

{!!todos.length && (
<Footer
handleFilter={handleFilter}
filter={filter}
todos={getFilteredTodos}
deleteTodo={deleteTodo}
activeTodos={activeTodos}
completedTodos={completedTodos}
/>
)}
</div>

<ErrorNotification errorMessage={errorMessage} />
</div>
);
};
20 changes: 20 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClient';

export const USER_ID = 1415;

export const getTodos = () => {
return client.get<Todo[]>(`/todos?userId=${USER_ID}`);
};

export const createTodo = ({ title, userId, completed }: Omit<Todo, 'id'>) => {
return client.post<Todo>('/todos/', { title, userId, completed });
};

export const updateTodo = ({ title, id, userId, completed }: Todo) => {
return client.patch<Todo>(`/todos/${id}`, { title, userId, completed });
};

export const deleteTodo = (id: number) => {
return client.delete(`/todos/${id}`);
};
26 changes: 26 additions & 0 deletions src/components/ErrorNotification/ErrorNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import classNames from 'classnames';
import React from 'react';

type Props = {
errorMessage: string;
};

export const ErrorNotification: React.FC<Props> = ({ errorMessage }) => {
return (
<div
data-cy="ErrorNotification"
className={classNames(
'notification',
'is-danger',
'is-light',
'has-text-weight-normal',
{
hidden: !errorMessage,
},
)}
>
<button data-cy="HideErrorButton" type="button" className="delete" />
{errorMessage}
</div>
);
};
1 change: 1 addition & 0 deletions src/components/ErrorNotification/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './ErrorNotification';
74 changes: 74 additions & 0 deletions src/components/Footer/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import classNames from 'classnames';
import React from 'react';

import { Todo } from '../../types/Todo';
import { FilterCriteria } from '../../types/FilterCriteria';

type Props = {
handleFilter: (filterType: FilterCriteria) => void;
filter: FilterCriteria;
todos: Todo[] | null;
deleteTodo: (todoId: number) => void;
activeTodos: number;
completedTodos: number;
};

const capitalizeFirstLetter = (str: string) => {
return str.charAt(0).toUpperCase() + str.slice(1);
};

export const Footer: React.FC<Props> = ({
handleFilter,
filter,
todos,
deleteTodo,
activeTodos,
completedTodos,
}) => {
const handleClearCompleted = () => {
todos?.forEach(todo => {
if (todo.completed) {
deleteTodo(todo.id);
}
});
};

const correctItemTerm = activeTodos === 1 ? 'item' : 'items';

return (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{activeTodos} {correctItemTerm} left
</span>

<nav className="filter" data-cy="Filter">
{Object.values(FilterCriteria).map(filterType => (
<a
key={filterType}
href={`#/${filterType}`}
className={classNames('filter__link', {
selected: filter === filterType,
})}
data-cy={`FilterLink${capitalizeFirstLetter(filterType)}`}
onClick={() => {
handleFilter(filterType);
}}
>
{capitalizeFirstLetter(filterType)}
</a>
))}
</nav>

{/* this button should be disabled if there are no completed todos */}
<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
onClick={handleClearCompleted}
disabled={completedTodos === 0}
>
Clear completed
</button>
</footer>
);
};
1 change: 1 addition & 0 deletions src/components/Footer/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './Footer';
Loading
Loading