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

need help #858

Open
wants to merge 4 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
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://hyper2307.github.io/react_todo-app-with-api/) and add it to the PR description.
35 changes: 19 additions & 16 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,27 @@
/* 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 { Header } from './components/Header';
import { TodoList } from './components/TodoList';
import { Footer } from './components/Footer';
import { TodosProvider } from './TodosContext/TodosContext';
import { ErrorsNotifications } from './components/ErrorsNotifications';

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

<div className="todoapp__content">
<Header />

<TodoList />

<Footer />
</div>

<p className="subtitle">Styles are already copied</p>
</section>
<ErrorsNotifications />
</div>
</TodosProvider>
);
};
93 changes: 93 additions & 0 deletions src/TodosContext/TodosContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import React, { useEffect, useState } from 'react';
import { Todo } from '../types/Todo';
import { getTodos } from '../api/todos';
import { USER_ID } from '../utils/USER_ID';
import { TodosContextType } from '../types/TodosContextType';
import { SortType } from '../types/SortType';

export const TodosContext = React.createContext<TodosContextType>({
todos: [],
setTodos: () => {},
errorMessage: '',
setErrorMessage: () => {},
preparedTodos: [],
sortQuery: '',
setSortQuery: () => {},
tempTodo: {
id: 0,
userId: 0,
title: '',
completed: false,
},
setTempTodo: () => {},
todosInProcess: [],
setTodosInProcess: () => {},
completedTodos: [],
});
Comment on lines +9 to +26

Choose a reason for hiding this comment

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

try reducing the amount of props in the component, it's bad practice to have big amount of props


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

export const TodosProvider: React.FC<Props> = ({ children }) => {
const [todos, setTodos] = useState<Todo[] | null>(null);
const [errorMessage, setErrorMessage] = useState('');
const [sortQuery, setSortQuery] = useState(SortType.All);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [todosInProcess, setTodosInProcess] = useState<number[]>([]);

useEffect(() => {
getTodos(USER_ID)
.then(todosFromServer => {
setTodos(() => {
if (todosFromServer) {
return todosFromServer;
}

return null;
});
})
.catch(() => {
setErrorMessage('Unable to load todos');
});
}, []);

const preparedTodos = sortQuery !== SortType.All
? (todos?.filter(todo => {
switch (sortQuery as SortType) {
case SortType.Active:
return !todo.completed;

default:
return todo.completed;
}
}) || todos)
: (
todos
);

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

return (
<TodosContext.Provider
value={{
todos,
setTodos,
errorMessage,
setErrorMessage,
preparedTodos,
sortQuery,
setSortQuery,
tempTodo,
setTempTodo,
todosInProcess,
setTodosInProcess,
completedTodos,
}}
>
{children}
</TodosContext.Provider>
);
};
26 changes: 26 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClient';

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

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

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

export const updateTodoTitle = (
todoId: number, data: { title: string },
) => {
return client.patch<Todo>(`/todos/${todoId}`, data);
};

export const updateTodoCompleted = (
todoId: number, data: { completed: boolean },
) => {
return client.patch<Todo>(`/todos/${todoId}`, data);
};
41 changes: 41 additions & 0 deletions src/components/ErrorsNotifications.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/* eslint-disable jsx-a11y/control-has-associated-label */
import React, { useEffect, useState } from 'react';
import cn from 'classnames';

import { useTodos } from '../hooks/useTodos';

export const ErrorsNotifications: React.FC = () => {
const { errorMessage } = useTodos();
const [isHidden, setIsHidden] = useState(true);

useEffect(() => {
setIsHidden(!!errorMessage);

setTimeout(() => setIsHidden(false), 3000);
}, [errorMessage]);

return (
<div
data-cy="ErrorNotification"
className={cn(
'notification',
'is-danger',
'is-light',
'has-text-weight-normal',
{
hidden: !isHidden,
},
)}
>
<button
data-cy="HideErrorButton"
type="button"
className="delete"
onClick={() => setIsHidden(false)}
/>
{
errorMessage
}
</div>
);
};
120 changes: 120 additions & 0 deletions src/components/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import React from 'react';
import cn from 'classnames';
import * as postService from '../api/todos';
import { useTodos } from '../hooks/useTodos';
import { SortType } from '../types/SortType';

export const Footer: React.FC = () => {
const {
todos,
setTodos,
setSortQuery,
sortQuery,
setTodosInProcess,
setErrorMessage,
} = useTodos();

const notCompletedTodosLength = todos?.filter(todo => (
!todo.completed
)).length || 0;

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

const clearCompleted = () => {
completedTodos?.forEach(todo => {
setTodosInProcess(prevTodosIds => [...prevTodosIds, todo.id]);

postService.removeTodo(todo.id)
.then(() => {
setTodos(prevTodos => {
if (prevTodos) {
return prevTodos.filter(currentTodo => (
currentTodo.id !== todo.id
));
}

return null;
});
})
.catch(() => setErrorMessage('Unable to delete a todo'))
.finally(() => setTodosInProcess(prevTodosIds => (
prevTodosIds.filter(id => todo.id !== id)
)));
});
};

return (
<>
{!!todos?.length && (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{notCompletedTodosLength}
{
notCompletedTodosLength <= 1
? ' item '
: ' items '
}
left
</span>

{/* Active filter should have a 'selected' class */}
<nav className="filter" data-cy="Filter">
<a
href="#/"
className={cn(
'filter__link',
{
selected: sortQuery === SortType.All,
},
)}
data-cy="FilterLinkAll"
onClick={() => setSortQuery(SortType.All)}
>
All
</a>

<a
href="#/active"
className={cn(
'filter__link',
{
selected: sortQuery === SortType.Active,
},
)}
data-cy="FilterLinkActive"
onClick={() => setSortQuery(SortType.Active)}
>
Active
</a>

<a
href="#/completed"
className={cn(
'filter__link',
{
selected: sortQuery === SortType.Completed,
},
)}
data-cy="FilterLinkCompleted"
onClick={() => setSortQuery(SortType.Completed)}
>
Completed
</a>
</nav>

<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
onClick={clearCompleted}
disabled={!completedTodos?.length}
>
Clear completed
</button>
</footer>
)}
</>
);
};
Loading
Loading