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 #1514

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
210 changes: 195 additions & 15 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,206 @@
/* eslint-disable max-len */
/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable @typescript-eslint/indent */
/* eslint-disable react-hooks/rules-of-hooks */
/* 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 {
getTodos,
createTodo,
updateTodo,
deleteTodo,
USER_ID,
} from './api/todos';
import { Todo } from './types/Todo';
import { Footer } from './components/Footer';
import { SelectedFilter } from './types/SelectedFilter';
import { Header } from './components/Header';
import { TodoList } from './components/TodoList';
import { ErrorSection } from './components/ErrorSection';
import { initialErrorMessage } from './constants/initialErrorMessage';

export const App: React.FC = () => {
if (!USER_ID) {
return <UserWarning />;
}

const [todos, setTodos] = useState<Todo[]>([]);
const [errorMessage, setErrorMessage] = useState(initialErrorMessage);
const [selectedFilter, setSelectedFilter] = useState<SelectedFilter>(
SelectedFilter.all,
);
const [titleNewTodo, setTitleNewTodo] = useState<string>('');
const [receiving, setReceiving] = useState<boolean>(false);
const [tempTodo, setTempTodo] = useState<string>('');
const [editingTitle, setEditingTitle] = useState<number>(0);
const [
updatingAndDeletingCompletedTodos,
setUpdatingAndDeletingCompletedTodos,
] = useState<Todo[] | []>([]);

const visibleTodos = todos.filter(todo => {
switch (selectedFilter) {
case SelectedFilter.all:
return true;

case SelectedFilter.active:
return !todo.completed;

case SelectedFilter.completed:
return todo.completed;
}
});

const itemLeft: number = todos.filter(todo => !todo.completed).length;
const completedTodos: Todo[] = todos.filter(todo => todo.completed);

function getAllTodos() {
getTodos()
.then(setTodos)
.catch(() => {
setErrorMessage({ ...errorMessage, load: true });
setInterval(() => {
setErrorMessage({ ...errorMessage, load: false });
}, 3000);
});
}

function addTodo({ title, completed, userId }: Omit<Todo, 'id'>) {
if (!title) {
setErrorMessage({ ...errorMessage, emptyTitle: true });
setInterval(() => {
setErrorMessage({ ...errorMessage, emptyTitle: false });
}, 3000);

return;
}

setReceiving(true);

setTempTodo(title);

createTodo({ title, completed, userId })
.then(newTodo => {
setTodos(currentTodos => [...currentTodos, newTodo]);
setTitleNewTodo('');
})
.catch(() => {
setErrorMessage({ ...errorMessage, create: true });
setInterval(() => {
setErrorMessage({ ...errorMessage, create: false });
}, 3000);
})
.finally(() => {
setReceiving(false);
setTempTodo('');
});
}

function changeTodo(updatedTodo: Todo) {
updateTodo(updatedTodo)
.then(todo => {
setTodos(currentTodos => {
const newTodos = [...currentTodos];
const index = newTodos.findIndex(task => task.id === updatedTodo.id);

newTodos.splice(index, 1, todo);

setEditingTitle(0);

return newTodos;
});
})
.catch(() => {
setErrorMessage({ ...errorMessage, updating: true });
setInterval(() => {
setErrorMessage({ ...errorMessage, updating: false });
}, 3000);
})
.finally(() => {
setUpdatingAndDeletingCompletedTodos(
updatingAndDeletingCompletedTodos?.filter(
todo => todo !== updatedTodo,
),
);
});
}

function removeTodo(todoId: number) {
deleteTodo(todoId)
.then(() => {
setTodos(currentTodos =>
currentTodos.filter(todo => todo.id !== todoId),
);
})
.catch(() => {
setErrorMessage({ ...errorMessage, delete: true });
setInterval(() => {
setErrorMessage({ ...errorMessage, delete: false });
}, 3000);
});
}

useEffect(() => {
getAllTodos();
}, []);

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}
visibleTodos={visibleTodos}
title={titleNewTodo}
setTitle={setTitleNewTodo}
addTodo={addTodo}
errorMessage={errorMessage}
setErrorMessage={setErrorMessage}
receiving={receiving}
setUpdatingAndDeletingCompletedTodos={
setUpdatingAndDeletingCompletedTodos
}
changeTodo={changeTodo}
editingTitle={editingTitle}
/>

{todos.length > 0 && (
<TodoList
visibleTodos={visibleTodos}
removeTodo={removeTodo}
tempTodo={tempTodo}
updatingAndDeletingCompletedTodos={
updatingAndDeletingCompletedTodos
}
setUpdatingAndDeletingCompletedTodos={
setUpdatingAndDeletingCompletedTodos
}
changeTodo={changeTodo}
editingTitle={editingTitle}
setEditingTitle={setEditingTitle}
/>
)}

{todos.length > 0 && (
<Footer
itemLeft={itemLeft}
selectedFilter={selectedFilter}
setSelectedFilter={setSelectedFilter}
completedTodos={completedTodos}
removeTodo={removeTodo}
setUpdatingAndDeletingCompletedTodos={
setUpdatingAndDeletingCompletedTodos
}
/>
)}
</div>

<ErrorSection
errorMessage={errorMessage}
setErrorMessage={setErrorMessage}
/>
</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 = 1844;

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

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

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

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

type Props = {
errorMessage: ErrorMessage;
setErrorMessage: (errorMessage: ErrorMessage) => void;
};

export const ErrorSection: React.FC<Props> = ({
errorMessage,
setErrorMessage,
}) => (
<div
data-cy="ErrorNotification"
className={classNames(
'notification',
'is-danger',
'is-light',
'has-text-weight-normal',
{
hidden:
!errorMessage.load &&
!errorMessage.delete &&
!errorMessage.create &&
!errorMessage.emptyTitle &&
!errorMessage.updating,
},
)}
>
<button
data-cy="HideErrorButton"
type="button"
className="delete"
onClick={() => {
setErrorMessage(initialErrorMessage);
}}
/>
{/* show only one message at a time */}
{errorMessage.load && 'Unable to load todos'}
{errorMessage.create && 'Unable to add a todo'}
{errorMessage.delete && 'Unable to delete a todo'}
{errorMessage.emptyTitle && 'Title should not be empty'}
{errorMessage.updating && 'Unable to update a todo'}
</div>
);
64 changes: 64 additions & 0 deletions src/components/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import classNames from 'classnames';
import { SelectedFilter } from '../types/SelectedFilter';
import { Todo } from '../types/Todo';

type Props = {
itemLeft: number;
selectedFilter: SelectedFilter;
setSelectedFilter: (filter: SelectedFilter) => void;
completedTodos: Todo[];
removeTodo: (todoId: number) => void;
setUpdatingAndDeletingCompletedTodos: (completedTodos: Todo[] | []) => void;
};

export const Footer: React.FC<Props> = ({
itemLeft,
selectedFilter,
setSelectedFilter,
completedTodos,
removeTodo,
setUpdatingAndDeletingCompletedTodos: setDeletingCompletedTodos,
}) => {
function deleteCompletedTodos() {
setDeletingCompletedTodos(completedTodos);
completedTodos.forEach(todo => removeTodo(todo.id));
}

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

{/* Active link should have the 'selected' class */}
<nav className="filter" data-cy="Filter">
{Object.values(SelectedFilter).map(button => {
return (
<a
key={button}
href={button === SelectedFilter.all ? '#/' : `#/${button}`}
className={classNames('filter__link', {
selected: selectedFilter === button,
})}
data-cy={`FilterLink${button}`}
onClick={() => setSelectedFilter(button)}
>
{button}
</a>
);
})}
</nav>

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