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 task solution #770

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
263 changes: 251 additions & 12 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,263 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import React, {
FormEvent, useEffect, useMemo, useState,
} from 'react';
import classNames from 'classnames';
import { Todo } from './types/Todo';
import { FilterType } from './types/FilterTypes';
import { Error } from './types/Error';
import { getTodos } from './api/todos';
import * as postService from './api/todos';
import { UserWarning } from './UserWarning';
import { TodoList } from './components/TodoList';
import { TodoFilter } from './components/FilterTodo';
import { TodoError } from './components/TodoError';
import { TodoItem } from './components/TodoItem';

const USER_ID = 0;
const USER_ID = 11707;

const getVisibleTodos = (todos: Todo[], status: FilterType) => {
return todos.filter(todo => {
switch (status) {
case FilterType.Completed:
return todo.completed;

case FilterType.Active:
return !todo.completed;

default:
return true;
}
});
};

export const App: React.FC = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [status, setStatus] = useState(FilterType.All);
const [errorMessage, setErrorMessage] = useState(Error.None);
const [query, setQuery] = useState('');
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [loadingIds, setLoadingIds] = useState<number[]>([]);

useEffect(() => {
getTodos(USER_ID)
.then(setTodos)
.catch(() => setErrorMessage(Error.Load));
}, []);

const visibleTodos = useMemo(() => getVisibleTodos(todos, status),
[todos, status]);

const todosCount = useMemo(() => todos.filter(todo => !todo.completed).length,
[todos]);

const isCompletedTodos = useMemo(() => todos.some(todo => todo.completed),
[todos]);

const completedTodoCount = todos.filter(todo => todo.completed).length;

const handleQuery = (event: React.ChangeEvent<HTMLInputElement>) => {
setQuery(event.target.value);
};

const handleSubmit = (event: FormEvent) => {
event.preventDefault();

if (query.trim() === '') {
setErrorMessage(Error.EmptyTitle);

return;
}

const newTodo = {
title: query,
completed: false,
userId: USER_ID,
};

setTempTodo({ ...newTodo, id: 0 });
setLoadingIds((ids) => [...ids, 0]);

postService.createTodo(newTodo)
.then((value) => {
setTodos(currentTodos => [...currentTodos, value]);
setTempTodo(null);
})
.catch((error) => {
setErrorMessage(Error.Add);
throw error;
})
.finally(() => {
setLoadingIds((ids) => ids.filter(id => id !== 0));
});

setQuery('');
};

const onDeleteTodo = (todoId: number) => {
setLoadingIds((ids) => [...ids, todoId]);
postService.deleteTodo(todoId)
.then(() => setTodos(
currentTodos => currentTodos.filter(
todo => todo.id !== todoId,
),
))
.catch(() => setErrorMessage(Error.Delete))
.finally(() => setLoadingIds((ids) => ids.filter(id => id !== todoId)));
};

const onDeleteCompleted = () => {
todos.filter(todo => todo.completed).forEach((todo) => {
onDeleteTodo(todo.id);
});
};

if (!USER_ID) {
return <UserWarning />;
}

const handleToggleAll = () => {
const uncompletedTodos = todos.filter(todo => todo.completed === false);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
const uncompletedTodos = todos.filter(todo => todo.completed === false);
const uncompletedTodos = todos.filter(todo => !todo.completed);

const uncompletedTodosIds = uncompletedTodos.map(todo => todo.id);

if (uncompletedTodos.length === 0) {
setLoadingIds(currentIds => [
...currentIds,
...todos.map(
todo => todo.id,
)]);

Promise.all(todos.map(todo => {
return postService.updateTodo(todo.id, {
completed: !todo.completed,
});
}))
.then(() => {
getTodos(USER_ID)
.then((value) => {
setTodos(value);
setLoadingIds([]);
})
.catch(() => {
setErrorMessage(Error.Load);
});
})
.catch(() => {
setErrorMessage(Error.Update);
});

return;
}

setLoadingIds(currentIds => [...currentIds, ...uncompletedTodosIds]);

Promise.all(uncompletedTodos.map(todo => {
return postService.updateTodo(todo.id, {
completed: !todo.completed,
});
}))
.then(() => {
getTodos(USER_ID)
.then((value) => {
setTodos(value);
setTodos(value);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why do we need to call it twice?

})
.catch(() => {
setErrorMessage(Error.Load);
})

.finally(() => {
setLoadingIds([]);
});
})
.catch(() => {
setErrorMessage(Error.Update);
});
};

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 className="todoapp__header">

{todos.length !== 0 && (
<button
type="button"
className={classNames('todoapp__toggle-all', {
active: completedTodoCount !== 0,
})}
onClick={() => handleToggleAll()}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
onClick={() => handleToggleAll()}
onClick={handleToggleAll}

we can simplify it

/>
)}
<form onSubmit={(event) => handleSubmit(event)}>
<input
type="text"
className="todoapp__new-todo"
placeholder="What needs to be done?"
value={query}
onChange={handleQuery}
/>
</form>
</header>

{!!todos.length && (
<>
<TodoList
todos={visibleTodos}
onDeleteTodo={onDeleteTodo}
loadingIds={loadingIds}
setTodos={setTodos}
setLoadingIds={setLoadingIds}
/>

{tempTodo && (
<TodoItem
todo={tempTodo}
onDeleteTodo={onDeleteTodo}
loadingIds={loadingIds}
setTodos={setTodos}
setLoadingIds={setLoadingIds}
todos={visibleTodos}

/>

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
todos={visibleTodos}
/>
todos={visibleTodos}
/>

)}

<footer className="todoapp__footer">
<span className="todo-count">
{todosCount === 1 ? ('1 item left')
: (`${todosCount} items left`)}
</span>

<TodoFilter
status={status}
onStatusChange={setStatus}
/>

<button
type="button"
className={classNames(
'todoapp__clear-completed',
{ 'todoapp__clear-completed--disabled': !isCompletedTodos },
)}
onClick={onDeleteCompleted}
>
Clear completed
</button>
</footer>
</>
)}
</div>

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

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

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

export const deleteTodo = (todoId: number) => {
return client.delete(`/todos/${todoId}`);
};

export const updateTodo = (
todoId: number,
data: { completed?: boolean, title?: string },
) => {
return client.patch(`/todos/${todoId}`, data);
};
43 changes: 43 additions & 0 deletions src/components/FilterTodo.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import classNames from 'classnames';
import { FilterType } from '../types/FilterTypes';

type Props = {
status: FilterType,
onStatusChange: (filter: FilterType) => void,
};

export const TodoFilter: React.FC<Props> = ({ status, onStatusChange }) => {
return (
<nav className="filter">
<a
href="#/"
className={classNames('filter__link', {
selected: status === FilterType.All,
})}
onClick={() => onStatusChange(FilterType.All)}
>
{FilterType.All}
</a>

<a
href="#/active"
className={classNames('filter__link', {
selected: status === FilterType.Active,
})}
onClick={() => onStatusChange(FilterType.Active)}
>
{FilterType.Active}
</a>

<a
href="#/completed"
className={classNames('filter__link', {
selected: status === FilterType.Completed,
})}
onClick={() => onStatusChange(FilterType.Completed)}
>
{FilterType.Completed}
</a>
</nav>
);
};
42 changes: 42 additions & 0 deletions src/components/TodoError.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { useEffect } from 'react';
import classNames from 'classnames';
import { Error } from '../types/Error';

type Props = {
error: Error,
onErrorChange: (error: Error) => void,
};

export const TodoError: React.FC<Props> = ({ error, onErrorChange }) => {
useEffect(() => {
let timeoutId: NodeJS.Timeout;

if (error) {
timeoutId = setTimeout(() => {
onErrorChange(Error.None);
}, 3000);
}

return () => {
if (timeoutId) {
clearTimeout(timeoutId);
}
};
}, [error, onErrorChange]);

return (
<div className={classNames('notification',
'is-danger is-light has-text-weight-normal', {
hidden: error === Error.None,
})}
>
<button
type="button"
className="delete"
onClick={() => onErrorChange(Error.None)}
aria-label="close the error window"
/>
{error}
</div>
);
};
Loading