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

Develop #1499

Open
wants to merge 19 commits into
base: master
Choose a base branch
from
224 changes: 212 additions & 12 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,226 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import React, { useEffect, useState } from 'react';
import { UserWarning } from './UserWarning';
import { USER_ID } from './api/todos';
import classNames from 'classnames';
import { Todo } from './types/Todo';
import * as todosFromServer from './api/todos';
import { wait } from './utils/fetchClient';
import { TodoForm } from './components/TodoForm/TodoForm';
import { TodoList } from './components/TodoList/TodoList';
import { TodoFooter } from './components/TodoFooter/TodoFooter';
import { Status } from './types/Status';
import { TodoItem } from './components/TodoItem/TodoItem';

const USER_ID = 0;
const getTodosByStatus = (status: string, todos: Todo[]) => {
const preperedTodos = [...todos];

if (status) {
switch (status) {
case Object.keys(Status)[Object.values(Status).indexOf(Status.active)]:
return preperedTodos.filter(todo => !todo.completed);
case Object.keys(Status)[Object.values(Status).indexOf(Status.completed)]:
return preperedTodos.filter(todo => todo.completed);
default:
return preperedTodos;
}
}

return preperedTodos;
};

export const App: React.FC = () => {
const [titleError, setTitleError] = useState(false);
const [todos, setTodos] = useState<Todo[]>([]);
const [loadError, setLoadError] = useState(false);
const [addError, setAddError] = useState(false);
const [deleteError, setDeleteError] = useState(false);
const [updateError, setUpdateError] = useState(false);
const [status, setStatus] = useState('all');
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [tempArray, setTempArray] = useState<Todo[]>([]);
const [edit, setEdit] = useState(false);

const temp = (currentTodo: Todo) => {
setTempArray(prevArray => [...prevArray, currentTodo]);
};

const filteredTodos = getTodosByStatus(status, todos);

async function addTodo(newTodoTitle: string) {
const editedTitle = newTodoTitle.trim();

if (!editedTitle) {
setTitleError(true);
wait(3000).then(() => setTitleError(false));

return;
} else {
setTempTodo({
id: 0,
userId: 839,
title: editedTitle,
completed: false,
});

return todosFromServer
.createTodos({
userId: 839,
title: editedTitle,
completed: false,
})
.then(newTodo => {
setTodos(prevTodos => [...prevTodos, newTodo]);
setTempTodo(null);
})
.catch(error => {
setAddError(true);
setTempTodo(null);
wait(3000).then(() => setAddError(false));
throw error;
});
}
}

async function updateTodo(
updatedTodo: Todo,
// successUpdateState?: VoidFunction,

Choose a reason for hiding this comment

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

Remove comments

Suggested change
// successUpdateState?: VoidFunction,

): Promise<void> {

Choose a reason for hiding this comment

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

It's important to use one way of creating functions, fix it everywhere

Suggested change
async function updateTodo(
updatedTodo: Todo,
// successUpdateState?: VoidFunction,
): Promise<void> {
const updateTodo = async (
updatedTodo: Todo,
// successUpdateState?: VoidFunction,
): Promise<void> => {

return todosFromServer
.updateTodos(updatedTodo)
.then((todo: Todo) => {
setTodos(currentTodos => {
const newTodos = [...currentTodos];
const index = newTodos.findIndex(
thisTodo => thisTodo.id === updatedTodo.id,
);

newTodos.splice(index, 1, todo);

return newTodos;
});
setEdit(false);
// successUpdateState?.();
})
.catch(error => {
setEdit(true);
setUpdateError(true);
wait(3000).then(() => setUpdateError(false));
setTempArray([]);
throw error;
});
}

const deleteTodo = (paramTodo: Todo) => {
todosFromServer
.deleteTodos(paramTodo.id)
.then(() =>
setTodos(prevTodos =>
prevTodos.filter(todo => todo.id !== paramTodo.id),
),
)
.catch(() => {
setDeleteError(true);
wait(3000).then(() => {
setDeleteError(false);
});
});
};

useEffect(() => {
todosFromServer
.getTodos()
.then(setTodos)
.catch(() => setLoadError(true));
wait(3000).then(() => setLoadError(false));
}, []);

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

const deleteCompletedTodos = (paramTodos: Todo[]) => {
paramTodos.forEach(todo => deleteTodo(todo));
};

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>
<div className="todoapp">
<h1 className="todoapp__title">todos</h1>

<div className="todoapp__content">
<header className="todoapp__header">
{/* Add a todo on form submit */}
<TodoForm
onSubmit={addTodo}
setTitleError={setTitleError}
todos={todos}
updateTodo={updateTodo}
setTempArray={temp}
edit={edit}
/>
</header>

<p className="subtitle">Styles are already copied</p>
</section>
<TodoList
todos={filteredTodos}
updateTodo={updateTodo}
deleteTodo={deleteTodo}
array={tempArray}
setTempArray={temp}
edit={edit}
/>

{tempTodo && (
<TodoItem
todo={tempTodo}
updateTodo={updateTodo}
deleteTodo={deleteTodo}
tempArray={tempArray}
setTempArray={temp}
edit={edit}
/>
)}

{!!todos.length && (
// {/* Hide the footer if there are no todos */}
<TodoFooter
todos={todos}
setStatus={setStatus}
status={status}
deleteCompletedTodos={deleteCompletedTodos}
/>
)}
</div>

{/* {error && ( */}
{/* DON'T use conditional rendering to hide the notification */}
{/* Add the 'hidden' class to hide the message smoothly */}
<div
data-cy="ErrorNotification"
className={classNames(
'notification is-danger is-light has-text-weight-normal',
{
hidden:
!titleError &&
!loadError &&
!addError &&
!deleteError &&
!updateError,
},
)}
>
<button data-cy="HideErrorButton" type="button" className="delete" />
{/* show only one message at a time */}
{loadError && 'Unable to load todos'}
<br />
{titleError && 'Title should not be empty'}
<br />
{addError && 'Unable to add a todo'}
<br />
{deleteError && 'Unable to delete a todo'}
<br />
{updateError && 'Unable to update a todo'}
</div>
</div>
);
};
32 changes: 32 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClient';

export const USER_ID = 839;
//https://mate.academy/students-api/todos?userId=839

Choose a reason for hiding this comment

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

Suggested change
//https://mate.academy/students-api/todos?userId=839


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

// Add more methods here

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

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

export const deleteTodos = (todoId: number) => {
return client.delete(`/todos/${todoId}`);
};
76 changes: 76 additions & 0 deletions src/components/TodoFooter/TodoFooter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import classNames from 'classnames';
import { Todo } from '../../types/Todo';
import { Status } from '../../types/Status';

type Props = {
todos: Todo[];
setStatus: (status: string) => void;
status: string;
deleteCompletedTodos: (todos: Todo[]) => void;
};

const getDataCYByStatus = (status: string) => {
switch (status) {
case Object.keys(Status)[Object.values(Status).indexOf(Status.active)]:
return 'FilterLinkActive';
case Object.keys(Status)[Object.values(Status).indexOf(Status.completed)]:
return 'FilterLinkCompleted';
default:
return 'FilterLinkAll';
}
};

export const TodoFooter: React.FC<Props> = ({
todos,
setStatus,
status,
deleteCompletedTodos,
}) => {
const itemsLeft = todos.filter(todo => !todo.completed).length;
const handleTodosStatus = (currentStatus: string) => {
setStatus(currentStatus);
};

const isOneComplited =
todos.filter(todo => todo.completed).length > 0 ? false : true;

const handleDeleteAllCompleted = () => {
deleteCompletedTodos(todos.filter(t => t.completed === true));
};

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

{/* Active link should have the 'selected' class */}
<nav className="filter" data-cy="Filter">
{Object.entries(Status).map(([key, value]) => (
<a
key={key}
href="#/"
className={classNames('filter__link', {
selected: status === key,
})}
data-cy={getDataCYByStatus(key)}
onClick={() => handleTodosStatus(key)}
>
{value}
</a>
))}
</nav>

{/* this button should be disabled if there are no completed todos */}
<button
disabled={isOneComplited}
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
onClick={handleDeleteAllCompleted}
>
Clear completed
</button>
</footer>
);
};
Loading
Loading