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

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 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://Koliras.github.io/react_todo-app-with-api/) and add it to the PR description.
25 changes: 13 additions & 12 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,25 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import { UserWarning } from './UserWarning';

const USER_ID = 0;
import { TodoApp } from './components/TodoApp/TodoApp';
import {
TodosContextProvider,
} from './components/TodosContextProvider/TodosContextProvider';
import { USER_ID } from './utils/UserId';
import {
ErrorContextProvider,
} from './components/ErrorContextProvider/ErrorContextProvider';

export const App: React.FC = () => {
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>
<TodosContextProvider>
<ErrorContextProvider>
<TodoApp />
</ErrorContextProvider>
</TodosContextProvider>
);
};
18 changes: 18 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClient';

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

export const postTodo = (data: Omit<Todo, 'id'>) => {
return client.post<Todo>('/todos', data);
};

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

export const updateTodo = (todoId: number, changes: object) => {

Choose a reason for hiding this comment

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

changes have to have another type instead of an object, as we update a todo in this case, and not every object suits.
You can use some of the utility types, for example, Partial.
https://www.typescriptlang.org/docs/handbook/utility-types.html

return client.patch(`/todos/${todoId}`, changes);
};
49 changes: 49 additions & 0 deletions src/components/ErrorContextProvider/ErrorContextProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import React, { useState } from 'react';

export const ErrorContext = React.createContext({
errorMessage: '',
setErrorMessage: () => {},
hasError: false,
setHasError: () => {},
onNewError: () => {},
} as ErrorContextProps);

type ErrorContextProps = {
errorMessage: string,
setErrorMessage: React.Dispatch<React.SetStateAction<string>>,
hasError: boolean,
setHasError: React.Dispatch<React.SetStateAction<boolean>>,
onNewError: (error: string) => void,
};

type Props = {
children: React.ReactNode,
};

export const ErrorContextProvider: React.FC<Props> = ({ children }) => {
const [errorMessage, setErrorMessage] = useState('');
const [hasError, setHasError] = useState(false);

const onNewError = (error: string) => {
setErrorMessage(error);
setHasError(true);

setTimeout(() => {
setHasError(false);
}, 3000);
};

const initialValue = {
errorMessage,
setErrorMessage,
hasError,
setHasError,
onNewError,
};

return (
<ErrorContext.Provider value={initialValue}>
{children}
</ErrorContext.Provider>
);
};
47 changes: 47 additions & 0 deletions src/components/Filter/Filter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import React from 'react';
import classNames from 'classnames';
import { FilterKey } from '../../types/FilterKey';

type Props = {
filterKey: FilterKey,
onClick: (key: FilterKey) => void
};

export const Filter: React.FC<Props> = ({ filterKey, onClick }) => {
return (
<nav className="filter" data-cy="Filter">
<a
data-cy="FilterLinkAll"
href="#/"
className={classNames('filter__link', {
selected: filterKey === FilterKey.All,
})}
onClick={() => onClick(FilterKey.All)}
>
All
</a>

<a
data-cy="FilterLinkActive"
href="#/active"
className={classNames('filter__link', {
selected: filterKey === FilterKey.Active,
})}
onClick={() => onClick(FilterKey.Active)}
>
Active
</a>

<a
data-cy="FilterLinkCompleted"
href="#/completed"
className={classNames('filter__link', {
selected: filterKey === FilterKey.Completed,
})}
onClick={() => onClick(FilterKey.Completed)}
>
Completed
</a>
</nav>
);
};
75 changes: 75 additions & 0 deletions src/components/NewTodo/NewTodo.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import React, {
useContext,
useEffect,
useRef,
useState,
} from 'react';
import { Todo } from '../../types/Todo';
import { postTodo } from '../../api/todos';
import { TodosContext } from '../TodosContextProvider/TodosContextProvider';
import { USER_ID } from '../../utils/UserId';
import { ErrorContext } from '../ErrorContextProvider/ErrorContextProvider';

type Props = {
setTempTodo: (todo: Todo | null) => void,
tempTodo: Todo | null,
};

export const NewTodo: React.FC<Props> = ({
setTempTodo, tempTodo,
}) => {
const { onNewError } = useContext(ErrorContext);
const { setTodos, todos } = useContext(TodosContext);
const [newTodoTitle, setNewTodoTitle] = useState('');
const titleInput = useRef<HTMLInputElement | null>(null);

useEffect(() => {
if (titleInput.current) {
titleInput.current.focus();
}
}, [todos, tempTodo]);

const handleAddingTodo = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();

if (!newTodoTitle.trim()) {
onNewError('Title should not be empty');

Choose a reason for hiding this comment

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

It would be good to put error texts in a separate constant.


return;
}

const newTodo: Omit<Todo, 'id'> = {
userId: USER_ID,
title: newTodoTitle.trim(),
completed: false,
};

postTodo(newTodo)
.then((response) => {
setNewTodoTitle('');
setTodos((prevTodos) => [...prevTodos, response]);
})
.catch(() => onNewError('Unable to add a todo'))
.finally(() => setTempTodo(null));

setTempTodo({
...newTodo,
id: 0,
});
};

return (
<form onSubmit={handleAddingTodo}>
<input
data-cy="NewTodoField"
ref={titleInput}
type="text"
className="todoapp__new-todo"
placeholder="What needs to be done?"
value={newTodoTitle}
onChange={(event) => setNewTodoTitle(event.target.value)}

Choose a reason for hiding this comment

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

Suggested change
onChange={(event) => setNewTodoTitle(event.target.value)}
onChange={({ target }) => setNewTodoTitle(target.value)}

disabled={!!tempTodo}
/>
</form>
);
};
156 changes: 156 additions & 0 deletions src/components/TodoApp/TodoApp.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import {
useContext,
useEffect,
useMemo,
useState,
} from 'react';
import classNames from 'classnames';
import { Filter } from '../Filter/Filter';
import { NewTodo } from '../NewTodo/NewTodo';
import { TodoList } from '../TodoList/TodoList';
import {
TodosContext,
} from '../TodosContextProvider/TodosContextProvider';
import { TodoError } from '../TodoError/TodoError';
import { deleteTodo, getTodos, updateTodo } from '../../api/todos';
import { FilterKey } from '../../types/FilterKey';
import { Todo } from '../../types/Todo';
import { USER_ID } from '../../utils/UserId';
import { ErrorContext } from '../ErrorContextProvider/ErrorContextProvider';

function getFilteredTodos(key: FilterKey, todos: Todo[]) {

Choose a reason for hiding this comment

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

I would move this to separate file as a helper function

switch (key) {
case FilterKey.All:
return todos;
case FilterKey.Active:
return todos.filter(({ completed }) => !completed);
case FilterKey.Completed:
return todos.filter(({ completed }) => completed);
default:
return todos;
}
}

export const TodoApp = () => {
const { onNewError } = useContext(ErrorContext);
const { todos, setTodos, setTodoIdsWithLoader } = useContext(TodosContext);
const [filterKey, setFilterKey] = useState<FilterKey>(FilterKey.All);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);

const areAllTodosCompleted = todos.every(({ completed }) => completed);

Choose a reason for hiding this comment

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

I know that "are" would be lexically correct, but in programming it is customary to use "is" in all cases :)

const visibleTodos = useMemo(
() => getFilteredTodos(filterKey, todos),
[todos, filterKey],
);
const activeTodos = todos.filter(({ completed }) => !completed);
const hasCompletedTodo = todos.some(({ completed }) => completed);

useEffect(() => {
getTodos(USER_ID)
.then(setTodos)
.catch(() => onNewError('Unable to load todos'));
}, []);

const handleAllTodosToggle = () => {
const todosToUpdate = todos.filter(
({ completed }) => completed === areAllTodosCompleted,
);

setTodoIdsWithLoader(
prevTodoIds => [...prevTodoIds, ...todosToUpdate.map(({ id }) => id)],
);

todosToUpdate.forEach(todo => {
updateTodo(todo.id, { completed: !todo.completed })
.then(() => {
const todosCopy = [...todos];
const searchedTodo = todos.find(
({ id }) => todo.id === id,
) as Todo;

searchedTodo.completed = !searchedTodo.completed;

setTodos(todosCopy);
})
.catch(() => onNewError('Unable to update a todo'))
.finally(() => setTodoIdsWithLoader(
prevTodoIds => prevTodoIds.filter((todoId) => todoId !== todo.id),
));
});
};

const handleCompletedTodosDelete = () => {
const completedTodos = todos.filter(({ completed }) => completed);

setTodoIdsWithLoader(prevTodoIds => {
return [...prevTodoIds, ...completedTodos.map(({ id }) => id)];
});

completedTodos.forEach(todo => {
deleteTodo(todo.id)
.then(() => {
setTodos(prevTodos => prevTodos.filter(({ id }) => id !== todo.id));
})
.catch(() => onNewError('Unable to delete a todo'))
.finally(() => setTodoIdsWithLoader(
prevTodoIds => prevTodoIds.filter((id) => todo.id !== id),
));
});
};

return (
<div className="todoapp">
<h1 className="todoapp__title">todos</h1>
<div className="todoapp__content">
<header className="todoapp__header">
{!!todos.length && (
<button
type="button"
data-cy="ToggleAllButton"
className={classNames('todoapp__toggle-all', {
active: areAllTodosCompleted,
})}
aria-label="toggle_all_todos"
onClick={handleAllTodosToggle}
/>
)}

<NewTodo
setTempTodo={setTempTodo}
tempTodo={tempTodo}
/>
</header>

<TodoList
todos={visibleTodos}
tempTodo={tempTodo}
/>

{!!todos.length && (
<footer className="todoapp__footer" data-cy="Footer">

Choose a reason for hiding this comment

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

I would move footer to separate component

<span className="todo-count" data-cy="TodosCounter">
{`${activeTodos.length} items left`}

Choose a reason for hiding this comment

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

If there is one item, there should not be a plural in the text.

Copy link
Author

@Koliras Koliras Sep 27, 2023

Choose a reason for hiding this comment

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

Firstly, I wrote a code that would not use plural to a single todo, but tests required it to be plural
image

</span>
<Filter
filterKey={filterKey}
onClick={setFilterKey}
/>
<button
type="button"
data-cy="ClearCompletedButton"
className={classNames('todoapp__clear-completed', {
'is-invisible': !hasCompletedTodo,
})}
onClick={handleCompletedTodosDelete}
disabled={!hasCompletedTodo}
>
Clear completed
</button>
</footer>
)}

<TodoError />
</div>
</div>
);
};
Loading