Skip to content
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://Sviatoslav593.github.io/react_todo-app-with-api/) and add it to the PR description.
1 change: 1 addition & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

292 changes: 278 additions & 14 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,290 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/label-has-associated-control */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import React, { useEffect, useState } from 'react';
import { UserWarning } from './UserWarning';

const USER_ID = 0;
import {
addTodos,
deleteTodos,
getTodos,
updateTodos,
USER_ID,
} from './api/todos';
import { TodoForm } from './components/TodoForm';
import { Todo } from './types/Todo';
import { TodoList } from './components/TodoList';
import { Footer } from './components/Footer';
import cn from 'classnames';
import { Selected } from './types/enums/Selected';
import { ErrorMessage } from './types/enums/ErrorMessage';

export const App: React.FC = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [selected, setSelected] = useState<Selected>(Selected.all);

const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [todoLoading, setTodoLoading] = useState(false);
const [todoIdLoading, setTodoIdLoading] = useState<number | null>(null);

const [todosIdsLoading, setTodosIdsLoading] = useState<number[]>([]);

const [visibleTodos, setVisibleTodos] = useState<Todo[]>([]);

useEffect(() => {
setVisibleTodos(
todos.filter(todo => {
if (selected === Selected.completed) {
return todo.completed;
}

if (selected === Selected.active) {
return !todo.completed;
}

return todos;
}),
);
}, [selected, todos]);

// const filteredTodos = todos.filter(todo => {
// if (filter === FilterField.completed) {
// return todo.completed;
// }

// if (filter === FilterField.active) {
// return !todo.completed;
// }

// return todos;
// });

const [errorMessage, setErrorMessage] = useState<ErrorMessage>(
ErrorMessage.noErrors,
);

useEffect(() => {
setErrorMessage(ErrorMessage.noErrors);

getTodos()
.then(setTodos)
.catch(() => setErrorMessage(ErrorMessage.loadError));
}, []);

useEffect(() => {
if (errorMessage) {
setTimeout(() => {
setErrorMessage(ErrorMessage.noErrors);
}, 3000);
}
}, [errorMessage]);

const handleActiveTodosButton = () => {
setSelected(Selected.active);
};

const handleCompletedTodosButton = () => {
setSelected(Selected.completed);
};

const handleAllTodosButton = () => {
setSelected(Selected.all);
};

const addTodo = (title: string) => {
setTodoLoading(true);
setErrorMessage(ErrorMessage.noErrors);
setTempTodo({
id: 0,
title: title,
userId: USER_ID,
completed: false,
});

return addTodos(title)
.then(newTodo => setTodos(currentTodos => [...currentTodos, newTodo]))
.catch(error => {
setErrorMessage(ErrorMessage.addError);
throw error;
})
.finally(() => {
setTempTodo(null);
setTodoLoading(false);
});
};

const deleteTodo = (todoId: number) => {
setTodoIdLoading(todoId);

return deleteTodos(todoId)
.then(() => {
setTodos(currentTodos => {
return [...currentTodos.filter(todo => todo.id !== todoId)];
});
})
.catch(error => {
setErrorMessage(ErrorMessage.deleteError);
setTodos(todos);
throw error;
})
.finally(() => {
setTodoIdLoading(null);
});
};

const updateTodo = (id: number, completed: boolean, title: string) => {
setErrorMessage(ErrorMessage.noErrors);
setTodoIdLoading(id);

return updateTodos(id, completed, title)
.then(updatedTodo => {
setTodos(currentTodos => {
const newTodos = [...currentTodos];
const index = newTodos.findIndex(todo => {
return todo.id === id;
});

newTodos.splice(index, 1, updatedTodo);

return newTodos;
});
})
.catch(error => {
setErrorMessage(ErrorMessage.updateError);

throw error;
})
.finally(() => setTodoIdLoading(null));
};

const SetAllTodosCompleted = () => {
const uncompletedTodos = todos.filter(todo => !todo.completed);
const completedTodos = todos.filter(todo => todo.completed);

const todosToMap =
todos.length === completedTodos.length ? todos : uncompletedTodos;

setTodosIdsLoading(uncompletedTodos.map(todo => todo.id));

return Promise.all(
todosToMap.map(uncompletedTodo => {
updateTodos(
uncompletedTodo.id,
!uncompletedTodo.completed,
uncompletedTodo.title,
)
.then(updatedTodo =>
setTodos(currentTodos => {
const newTodos = [...currentTodos];
const index = currentTodos.findIndex(
todo => todo.id === updatedTodo.id,
);

newTodos.splice(index, 1, updatedTodo);

return newTodos;
}),
)
.catch(() => {
setErrorMessage(ErrorMessage.updateError);
})
.finally(() => setTodosIdsLoading([]));
}),
);
};

const handleAllActiveDelete = () => {
setTodoLoading(true);

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

setTodosIdsLoading(completedTodos.map(todo => todo.id));

return Promise.all(
completedTodos.map(completedTodo =>
deleteTodos(completedTodo.id)
.then(() => {
setTodos(current =>
current.filter(todo => todo.id !== completedTodo.id),
);
})
.catch(() => {
setErrorMessage(ErrorMessage.deleteError);
}),
),
).finally(() => setTodosIdsLoading([]));
};

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

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
setError={setErrorMessage}
onAdd={addTodo}
setAllCompleted={SetAllTodosCompleted}
todos={todos}
/>
</header>
{todos && errorMessage !== 'Unable to load todos' && (
<TodoList
tempTodo={tempTodo}
isLoading={todoLoading}
todoIdLoading={todoIdLoading}
todos={visibleTodos}
onDelete={deleteTodo}
todosIdsLoading={todosIdsLoading}
updateTodo={updateTodo}
/>
)}

{/* Hide the footer if there are no todos */}
{todos.length > 0 && (
<Footer
handleActiveTodosButton={handleActiveTodosButton}
handleCompletedTodosButton={handleCompletedTodosButton}
handleAllTodosButton={handleAllTodosButton}
todos={todos}
selected={selected}
handleAllActiveDelete={handleAllActiveDelete}
/>
)}
</div>

<p className="subtitle">Styles are already copied</p>
</section>
{/* DON'T use conditional rendering to hide the notification */}
{/* Add the 'hidden' class to hide the message smoothly */}

<div
data-cy="ErrorNotification"
className={cn(
'notification is-danger is-light has-text-weight-normal',
{
hidden: !errorMessage,
},
)}
>
<button
onClick={() => setErrorMessage(ErrorMessage.noErrors)}
data-cy="HideErrorButton"
type="button"
className="delete"
/>
{/* show only one message at a time */}
{errorMessage}
<br />
{/* Title should not be empty
<br />
Unable to add a todo
<br />
Unable to delete a todo
<br />
Unable to update a todo */}
</div>
</div>
);
};
40 changes: 40 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClient';

export const USER_ID = 4147;

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

// Add more methods here

export const addTodos = (
title: string,
completed = false,
userId = USER_ID,
) => {
return client.post<Todo>(`/todos`, {
title,
completed,
userId,
});
};

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

export const updateTodos = (
todoId: number,
completed: boolean,
title?: string,
userId = USER_ID,
) => {
return client.patch<Todo>(`/todos/${todoId}`, {
todoId,
completed,
title,
userId,
});
};
Loading
Loading