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

initial commit #765

Open
wants to merge 1 commit 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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,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://aliliolek.github.io/react_todo-app-with-api/) and add it to the PR description.
198 changes: 186 additions & 12 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,198 @@
/* 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 {
createTodo,
deleteTodo,
editTodo,
getTodos,
} from './api/todos';
import { Todo } from './types/Todo';
import { TodoFilter } from './types/TodoFilter';
import { Header } from './components/Header';
import { TodoList } from './components/TodoList';
import { Footer } from './components/Footer';
import { Notifications } from './components/Notifications';

const USER_ID = 0;
const USER_ID = 11399;

export const App: React.FC = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [visibleTodos, setVisibleTodos] = useState<Todo[]>([]);
const [errors, setErrors] = useState({

Choose a reason for hiding this comment

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

use enum instead of object, where default value is Error.Empty:

enum Error {
  Empty = ''
  // other errors
}

load: false,
delete: false,
empty: false,
add: false,
edit: false,
});
const [currentFilter, setCurrentFilter] = useState(TodoFilter.All);
const [loadingId, setLoadingId] = useState<number[]>([]);

Choose a reason for hiding this comment

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

Suggested change
const [loadingId, setLoadingId] = useState<number[]>([]);
const [loadingTodoIds, setLoadingTodoIds] = useState<number[]>([]);

array - use plural form

const [tempTodo, setTempTodo] = useState<Todo | null>(null);

const filterTodos = (initTodos?: Todo[]) => {
let filtered;

if (initTodos) {
filtered = [...initTodos];
} else {
filtered = [...todos];
}
Comment on lines +36 to +40

Choose a reason for hiding this comment

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

you should get rid of it - make todos argument mandatory


switch (currentFilter) {
case TodoFilter.Active:
filtered = filtered.filter(todo => !todo.completed);
break;
case TodoFilter.Completed:
filtered = filtered.filter(todo => todo.completed);
break;
default:
break;
}

setVisibleTodos(filtered);
};

const loadTodos = () => {
getTodos(USER_ID).then(items => {
setTodos([...items]);
filterTodos(items);
}).catch(() => {
setErrors(prevErrors => ({ ...prevErrors, load: true }));
});
};

const removeTodo = (todoId: number) => {
setLoadingId(prevTodoId => [...prevTodoId, todoId]);

deleteTodo(todoId)
.then(() => {
setTodos(prevTodos => prevTodos
.filter(todo => todo.id !== todoId));
setLoadingId([]);
})
.catch(() => {
setErrors(prevErrors => ({
...prevErrors,
delete: true,
}));
setLoadingId([]);
});
};

const addTodo = (newTitle: string) => {
const maxId = Math.max(...todos.map(todo => todo.id));

setTempTodo({
id: 0,
title: newTitle,
completed: false,
userId: USER_ID,
});

createTodo({
id: maxId + 1,
title: newTitle,
completed: false,
userId: USER_ID,
})
.then((newTodo) => {
setTodos(prevTodos => [...prevTodos, newTodo]);
setTempTodo(null);
})
.catch(() => {
setErrors(prevErrors => ({
...prevErrors,
add: true,
}));
setTempTodo(null);
});
};

const changeTodo = (
property: string,
// eslint-disable-next-line @typescript-eslint/no-explicit-any

Choose a reason for hiding this comment

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

why any? try to figure out with types (maybe boolean | string, etc)

value: any,
todoId: number,
) => {
setLoadingId(prevTodoId => [...prevTodoId, todoId]);
const oldTodo = todos.find((todo) => todo.id === todoId);

if (oldTodo) {
const updatedTodo: Todo = { ...oldTodo, [property]: value };

editTodo(updatedTodo, todoId)
.then(editedTodo => {
setTodos(prevTodos => {
const newTodos = [...prevTodos];

const index = newTodos.findIndex(todo => todo.id === todoId);

newTodos.splice(index, 1, editedTodo);

return newTodos;
});
setLoadingId([]);
})
.catch(() => {
setErrors(prevErrors => ({
...prevErrors,
edit: true,
}));
setLoadingId([]);
});
}
};

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

useEffect(() => {
filterTodos();
}, [currentFilter, todos]);
Comment on lines +151 to +153

Choose a reason for hiding this comment

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

you don't need visibleTodos state
general rule if you calculate some value based on other state values/props no need to save it in state

save it in a common variable, wrap in useMemo with the same dependency array


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>

<p className="subtitle">Styles are already copied</p>
</section>
<div className="todoapp">
<h1 className="todoapp__title">todos</h1>
<div className="todoapp__content">
<Header
addTodo={addTodo}
todos={todos}
changeTodo={changeTodo}
setErrors={setErrors}
/>

{todos.length > 0 && (
<TodoList
todos={visibleTodos}
loadingId={loadingId}
removeTodo={removeTodo}
tempTodo={tempTodo}
changeTodo={changeTodo}
/>
)}

{todos.length > 0 && (
<Footer
currentFilter={currentFilter}
setCurrentFilter={setCurrentFilter}
todos={todos}
removeTodo={removeTodo}
/>
)}
</div>

{/* Notification is shown in case of any error */}
{/* Add the 'hidden' class to hide the message smoothly */}
<Notifications
errors={errors}
setErrors={setErrors}
/>
</div>
);
};
19 changes: 19 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClient';

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

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

export const createTodo = (todoData: Todo) => {
return client.post<Todo>('/todos', todoData);
};

export const editTodo = (todoData: Todo, todoId: number) => {
return client.patch<Todo>(`/todos/${todoId}`, todoData);
};
10 changes: 10 additions & 0 deletions src/components/Footer/Footer.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
.todoapp__clear-completed {
opacity: 1;
cursor: pointer;

&--hidden {
opacity: 0;
cursor: default;
transition: all 0.3s ease-in-out;
}
}
95 changes: 95 additions & 0 deletions src/components/Footer/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import classNames from 'classnames';
import { TodoFilter } from '../../types/TodoFilter';
import { Todo } from '../../types/Todo';
import './Footer.scss';

type FooterProps = {
currentFilter: TodoFilter;
setCurrentFilter: React.Dispatch<React.SetStateAction<TodoFilter>>;
todos: Todo[];
removeTodo: (todoId: number) => void;
};

export const Footer: React.FC<FooterProps> = ({
currentFilter,
setCurrentFilter,
todos,
removeTodo,
}) => {
const counterActive = todos.filter(todo => !todo.completed).length || 0;
const counterCompleted = todos.length - counterActive;

const handleFilter = (filterParam: TodoFilter) => {
setCurrentFilter(filterParam);
};

const clearCompleted = () => {
todos.forEach(todo => {
if (todo.completed) {
removeTodo(todo.id);
}
});
};

return (
<footer className="todoapp__footer">
<span className="todo-count">
{`${counterActive} items left`}
</span>

{/* Active filter should have a 'selected' class */}
<nav className="filter">
<a
href="#/"
className={classNames(
'filter__link',
{ selected: currentFilter === TodoFilter.All },
)}
onClick={() => {
handleFilter(TodoFilter.All);
}}
>
{TodoFilter.All}
</a>

<a
href="#/active"
className={classNames(
'filter__link',
{ selected: currentFilter === TodoFilter.Active },
)}
onClick={() => {
handleFilter(TodoFilter.Active);
}}
>
{TodoFilter.Active}
</a>

<a
href="#/completed"
className={classNames(
'filter__link',
{ selected: currentFilter === TodoFilter.Completed },
)}
onClick={() => {
handleFilter(TodoFilter.Completed);
}}
>
{TodoFilter.Completed}
</a>
</nav>

{/* don't show this button if there are no completed todos */}
<button
type="button"
className={classNames(
'todoapp__clear-completed',
{ 'todoapp__clear-completed--hidden': !counterCompleted },
)}
onClick={clearCompleted}
>
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