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 working version #813

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://dpidlutska.github.io/react_todo-app-with-api/) and add it to the PR description.
65 changes: 48 additions & 17 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,55 @@
/* 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 React, {
useContext,
useEffect, useMemo, useState,
} from 'react';
import { TodoForm } from './components/TodoForm';
import { TodoList } from './components/TodoList';
import { TodoFilter } from './components/TodoFilter';
import * as todoService from './api/todos';
import { TodosFilter } from './types/TodosFilter';
import { getFilteredTodos } from './utils/getFilteredTodos';
import { TodoContext } from './Context/TodoContext';
import { ErrorNotification } from './components/ErrorNotification';

export const App: React.FC = () => {
if (!USER_ID) {
return <UserWarning />;
}
const {
todos,
setTodos,
setErrorMessage,
} = useContext(TodoContext);

const [filter, setFilter] = useState(TodosFilter.All);

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

Check warning on line 29 in src/App.tsx

View workflow job for this annotation

GitHub Actions / run_linter (14.x)

React Hook useEffect has missing dependencies: 'setErrorMessage' and 'setTodos'. Either include them or remove the dependency array

const filteredTodos = useMemo(() => {
return getFilteredTodos(todos, filter);
}, [todos, filter]);

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">
<TodoForm />
<TodoList
todos={filteredTodos}
/>
{Boolean(todos.length) && (
<TodoFilter
filter={filter}
onFilterChange={setFilter}
/>
)}

<p className="subtitle">Styles are already copied</p>
</section>
</div>
<ErrorNotification />
</div>
);
};
176 changes: 176 additions & 0 deletions src/Context/TodoContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
import React, { createContext, useMemo, useState } from 'react';
import { Todo } from '../types/Todo';
import { USER_ID } from '../utils/constants';
import * as todoService from '../api/todos';
import { getCompletedTodos, getUncompletedTodos } from '../utils/countTodos';

interface TodoContextTypes {
todos: Todo[];
setTodos: React.Dispatch<React.SetStateAction<Todo[]>>;
completedTodos: Todo[];
uncompletedTodos: Todo[];
errorMessage: string;
setErrorMessage: React.Dispatch<React.SetStateAction<string>>;
tempTodo: Todo | null;
setTempTodo: React.Dispatch<React.SetStateAction<Todo | null>>;
todosIdToProcess: number[];
setTodosIdToProcess: React.Dispatch<React.SetStateAction<number[]>>;
handleAddTodo: (todoTitle: string) => Promise<void>;
handleDeleteTodo: (todoId: number) => void;
handleRenameTodo: (todo: Todo, newTodoTitle: string) => void;
handleClearCompletedTodos: () => void;
handleStatusTodoChange: (todo: Todo) => void;
}

const initTodoContext: TodoContextTypes = {
todos: [],
setTodos: () => {},
completedTodos: [],
uncompletedTodos: [],
errorMessage: '',
setErrorMessage: () => {},
tempTodo: null,
setTempTodo: () => {},
todosIdToProcess: [],
setTodosIdToProcess: () => {},
handleAddTodo: async () => {},
handleDeleteTodo: () => {},
handleRenameTodo: () => {},
handleClearCompletedTodos: () => {},
handleStatusTodoChange: () => {},
};

export const TodoContext = createContext(initTodoContext);

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

export const TodoProvider: React.FC<Props> = ({ children }) => {
const [todos, setTodos] = useState<Todo[]>([]);
const [errorMessage, setErrorMessage] = useState('');
const [todosIdToProcess, setTodosIdToProcess] = useState<number[]>([]);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const completedTodos = getCompletedTodos(todos);
const uncompletedTodos = getUncompletedTodos(todos);

const handleAddTodo = (todoTitle: string) => {
setTempTodo({
id: 0,
title: todoTitle,
userId: USER_ID,
completed: false,
});

return todoService
.addTodo(todoTitle)
.then((newTodo) => {
setTodos((prevTodos) => [...prevTodos, newTodo]);
})
.catch((error) => {
setErrorMessage('Unable to add a todo');
throw error;
})
.finally(() => {
setTempTodo(null);
});
};

const handleDeleteTodo = (todoId: number) => {
setTodosIdToProcess(prevState => [...prevState, todoId]);

todoService
.deleteTodo(todoId)
.then(() => {
setTodos(prevTodos => prevTodos.filter(({ id }) => id !== todoId));
})
.catch(() => {
setErrorMessage('Unable to delete a todo');
})
.finally(() => {
setTodosIdToProcess(prevState => prevState.filter(id => id !== todoId));
});
};

const handleRenameTodo = (todo: Todo, newTodoTitle: string) => {
setTodosIdToProcess(prevState => [...prevState, todo.id]);
todoService
.updateTodo({
id: todo.id,
title: newTodoTitle,
userId: todo.userId,
completed: todo.completed,
})
.then(updatedTodo => {
setTodos(prevTodos => prevTodos.map(currentTodo => (
currentTodo.id !== updatedTodo.id
? currentTodo
: updatedTodo
)));
})
.catch((error) => {
setErrorMessage('Unable to update a todo');
throw error;
})
.finally(() => {
setTodosIdToProcess(
prevState => prevState.filter(id => id !== todo.id),
);
});
};

const handleClearCompletedTodos = () => {
completedTodos.forEach(todo => (
handleDeleteTodo(todo.id)));
};

const handleStatusTodoChange = (todo: Todo) => {
setTodosIdToProcess(prevState => [...prevState, todo.id]);
todoService
.updateTodo({
...todo,
completed: !todo.completed,
})
.then(updatedTodo => {
setTodos(prevTodos => prevTodos.map(currentTodo => (
currentTodo.id !== updatedTodo.id
? currentTodo
: updatedTodo
)));
})
.catch(() => {
setErrorMessage('Unable to update a todo');
})
.finally(() => {
setTodosIdToProcess(
prevState => prevState.filter(id => id !== todo.id),
);
});
};

const value = useMemo(() => ({
todos,
setTodos,
completedTodos,
uncompletedTodos,
errorMessage,
setErrorMessage,
tempTodo,
setTempTodo,
todosIdToProcess,
setTodosIdToProcess,
handleAddTodo,
handleDeleteTodo,
handleRenameTodo,
handleClearCompletedTodos,
handleStatusTodoChange,
}), [todos, errorMessage, tempTodo, todosIdToProcess]);

Check warning on line 167 in src/Context/TodoContext.tsx

View workflow job for this annotation

GitHub Actions / run_linter (14.x)

React Hook useMemo has missing dependencies: 'completedTodos', 'handleClearCompletedTodos', and 'uncompletedTodos'. Either include them or remove the dependency array

return (
<TodoContext.Provider
value={value}
>
{children}
</TodoContext.Provider>
);
};
29 changes: 29 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClient';
import { USER_ID } from '../utils/constants';

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

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

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

export const updateTodo = ({
id, title, userId, completed,
}: Todo): Promise<Todo> => {
return client.patch(`/todos/${id}`, {
title,
userId,
completed,
});
};
42 changes: 42 additions & 0 deletions src/components/ErrorNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/* eslint-disable jsx-a11y/control-has-associated-label */
import React, { useContext, useEffect, useRef } from 'react';
import cn from 'classnames';
import { TodoContext } from '../Context/TodoContext';

export const ErrorNotification: React.FC = () => {
const {
errorMessage,
setErrorMessage,
} = useContext(TodoContext);

const timerId = useRef(0);

useEffect(() => {
if (timerId.current) {
window.clearTimeout(timerId.current);
}

timerId.current = window.setTimeout(() => {
setErrorMessage('');
}, 3000);
}, [errorMessage]);

Check warning on line 22 in src/components/ErrorNotification.tsx

View workflow job for this annotation

GitHub Actions / run_linter (14.x)

React Hook useEffect has a missing dependency: 'setErrorMessage'. Either include it or remove the dependency array

return (
<div
data-cy="ErrorNotification"
className={cn(
'notification is-danger is-light has-text-weight-normal', {
hidden: !errorMessage,
},
)}
>
<button
data-cy="HideErrorButton"
type="button"
className="delete"
onClick={() => setErrorMessage('')}
/>
{errorMessage}
</div>
);
};
Loading
Loading