-
Notifications
You must be signed in to change notification settings - Fork 1.5k
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 #1496
Open
Ostkreuzzz
wants to merge
2
commits into
mate-academy:master
Choose a base branch
from
Ostkreuzzz:develop
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
develop #1496
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,26 +1,142 @@ | ||
/* eslint-disable max-len */ | ||
/* eslint-disable jsx-a11y/label-has-associated-control */ | ||
/* eslint-disable jsx-a11y/control-has-associated-label */ | ||
import React from 'react'; | ||
import { UserWarning } from './UserWarning'; | ||
import React, { useEffect, useState, useCallback } from 'react'; | ||
import { getTodos } from './api/todos'; | ||
|
||
const USER_ID = 0; | ||
import { Todo } from './types/Todo'; | ||
import { ErrorMessages } from './types/ErrorTypes'; | ||
import { FilterTypes } from './types/FilterTypes'; | ||
|
||
import { getVisibleTodos } from './utils/getVisibleTodos'; | ||
import { handleError } from './utils/handleError'; | ||
|
||
import * as todoService from './api/todos'; | ||
|
||
import { TodoHeader } from './components/TodoHeader'; | ||
import { TodoList } from './components/TodoList'; | ||
import { TodoFooter } from './components/TodoFooter'; | ||
import { ErrorPannel } from './components/ErrorPannel'; | ||
|
||
export const App: React.FC = () => { | ||
if (!USER_ID) { | ||
return <UserWarning />; | ||
const [todos, setTodos] = useState<Todo[]>([]); | ||
const [tempTodo, setTempTodo] = useState<Todo | null>(null); | ||
const [todosToDelete, setTodosToDelete] = useState<number[]>([]); | ||
|
||
const [selectedFilterType, setSelectedFilterType] = useState<FilterTypes>( | ||
FilterTypes.ALL, | ||
); | ||
const [errorMessage, setErrorMessage] = useState<ErrorMessages>( | ||
ErrorMessages.NONE, | ||
); | ||
|
||
function handleUpload() { | ||
getTodos() | ||
.then(setTodos) | ||
.catch(() => handleError(setErrorMessage, ErrorMessages.LOAD_FAIL)); | ||
} | ||
|
||
const filteredTodos = getVisibleTodos(todos, selectedFilterType); | ||
const activeTodosCount = todos.filter(todo => !todo.completed).length; | ||
const completedIds = todos | ||
.filter(todo => todo.completed) | ||
.map(todo => todo.id); | ||
|
||
function handleClearCompleted() { | ||
setTodosToDelete(completedIds); | ||
} | ||
|
||
const deleteTodos = useCallback( | ||
(idsToDelete: number[]) => { | ||
Promise.allSettled( | ||
idsToDelete.map(id => { | ||
todoService | ||
.deleteTodo(id) | ||
.then(() => { | ||
setTodos(prevTodos => prevTodos.filter(todo => todo.id !== id)); | ||
setTodosToDelete(() => []); | ||
}) | ||
.catch(() => { | ||
setTodos(todos); | ||
handleError(setErrorMessage, ErrorMessages.DELETE_FAIL); | ||
setTodosToDelete(() => []); | ||
}); | ||
}), | ||
); | ||
}, | ||
[setTodos, setTodosToDelete, setErrorMessage, todos], | ||
); | ||
|
||
function addTodo({ title, userId, completed }: Todo) { | ||
return todoService | ||
.addTodo({ title, userId, completed }) | ||
.then(newTodo => { | ||
setTodos([...todos, newTodo]); | ||
setTempTodo(null); | ||
}) | ||
.catch(error => { | ||
setTempTodo(null); | ||
handleError(setErrorMessage, ErrorMessages.ADD_FAIL); | ||
|
||
throw error; | ||
}); | ||
} | ||
|
||
const updateTodo = useCallback((todo: Todo) => { | ||
return todoService | ||
.updateTodo(todo.id, todo) | ||
.then(updatedTodo => { | ||
setTodos(current => | ||
current.map(currentTodo => | ||
currentTodo.id === updatedTodo.id ? updatedTodo : currentTodo, | ||
), | ||
); | ||
}) | ||
.catch(error => { | ||
handleError(setErrorMessage, ErrorMessages.UPDATE_FAIL); | ||
throw error; | ||
}); | ||
}, []); | ||
|
||
useEffect(handleUpload, [todosToDelete.length]); | ||
|
||
useEffect(() => { | ||
if (todosToDelete.length > 0) { | ||
deleteTodos(todosToDelete); | ||
} | ||
}, [deleteTodos, todosToDelete]); | ||
|
||
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"> | ||
<TodoHeader | ||
onTempTodo={setTempTodo} | ||
onErrorMessage={setErrorMessage} | ||
onAdd={addTodo} | ||
onUpdate={updateTodo} | ||
todos={todos} | ||
/> | ||
{!!todos.length && ( | ||
<> | ||
<TodoList | ||
onTodosToDelete={setTodosToDelete} | ||
todos={filteredTodos} | ||
todosToDelete={todosToDelete} | ||
tempTodo={tempTodo} | ||
onUpdate={updateTodo} | ||
/> | ||
<TodoFooter | ||
onSelectedFilterType={setSelectedFilterType} | ||
selectedFilterType={selectedFilterType} | ||
activeTodosCount={activeTodosCount} | ||
completedTodosIds={completedIds} | ||
clearCompletedTodos={handleClearCompleted} | ||
/> | ||
</> | ||
)} | ||
</div> | ||
<ErrorPannel errorMessage={errorMessage} /> | ||
</div> | ||
); | ||
}; |
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 = 1633; | ||
|
||
export const getTodos = (): Promise<Todo[]> => { | ||
return client.get<Todo[]>(`/todos?userId=${USER_ID}`); | ||
}; | ||
|
||
export const deleteTodo = (userId: number) => { | ||
return client.delete(`/todos/${userId}`); | ||
}; | ||
|
||
export const addTodo = ({ title, userId, completed }: Omit<Todo, 'id'>) => { | ||
return client.post<Todo>(`/todos`, { title, userId, completed }); | ||
}; | ||
|
||
export const updateTodo = (userId: number, data: Todo) => { | ||
return client.patch<Todo>(`/todos/${userId}`, data); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
import React from 'react'; | ||
import cn from 'classnames'; | ||
import { ErrorMessages } from '../types/ErrorTypes'; | ||
|
||
interface Props { | ||
errorMessage: ErrorMessages; | ||
} | ||
|
||
export const ErrorPannel: React.FC<Props> = ({ errorMessage }) => { | ||
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={cn('delete', { hidden: !errorMessage })} | ||
/> | ||
{errorMessage} | ||
</div> | ||
); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
import cn from 'classnames'; | ||
import { FilterTypes } from '../types/FilterTypes'; | ||
|
||
interface Props { | ||
onSelectedFilterType: (type: FilterTypes) => void; | ||
clearCompletedTodos: () => void; | ||
selectedFilterType: FilterTypes; | ||
activeTodosCount: number; | ||
completedTodosIds: number[]; | ||
} | ||
|
||
export const TodoFooter: React.FC<Props> = ({ | ||
clearCompletedTodos, | ||
onSelectedFilterType, | ||
selectedFilterType, | ||
activeTodosCount, | ||
completedTodosIds, | ||
}) => { | ||
return ( | ||
<footer className="todoapp__footer" data-cy="Footer"> | ||
<span className="todo-count" data-cy="TodosCounter"> | ||
{activeTodosCount} items left | ||
</span> | ||
|
||
<nav className="filter" data-cy="Filter"> | ||
{Object.values(FilterTypes).map(value => ( | ||
<a | ||
key={value} | ||
href={value === FilterTypes.ALL ? `#/` : `#/${value.toLowerCase()}`} | ||
className={cn('filter__link', { | ||
selected: selectedFilterType === value, | ||
})} | ||
data-cy={`FilterLink${value}`} | ||
onClick={() => onSelectedFilterType(value)} | ||
> | ||
{value} | ||
</a> | ||
))} | ||
</nav> | ||
|
||
<button | ||
type="button" | ||
className="todoapp__clear-completed" | ||
data-cy="ClearCompletedButton" | ||
disabled={!completedTodosIds.length} | ||
onClick={clearCompletedTodos} | ||
> | ||
Clear completed | ||
</button> | ||
</footer> | ||
); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,113 @@ | ||
import { useEffect, useRef, useState } from 'react'; | ||
import cn from 'classnames'; | ||
import { USER_ID } from '../api/todos'; | ||
|
||
import { ErrorMessages } from '../types/ErrorTypes'; | ||
import { Todo } from '../types/Todo'; | ||
|
||
import { handleError } from '../utils/handleError'; | ||
|
||
interface Props { | ||
onTempTodo: (todo: Todo | null) => void; | ||
onErrorMessage: (type: ErrorMessages) => void; | ||
onAdd: (todo: Todo) => Promise<void>; | ||
onUpdate: (todos: Todo) => Promise<void>; | ||
todos: Todo[]; | ||
} | ||
|
||
export const TodoHeader: React.FC<Props> = ({ | ||
todos, | ||
onAdd, | ||
onUpdate, | ||
onErrorMessage, | ||
onTempTodo, | ||
}) => { | ||
const [title, setTitle] = useState(''); | ||
const [isSubmiting, setIsSubmiting] = useState(false); | ||
|
||
const isAllCompleted = | ||
todos.every(todo => todo.completed) && todos.length !== 0; | ||
|
||
const todoInput = useRef<HTMLInputElement>(null); | ||
|
||
const handleSubmit = (event: React.FormEvent) => { | ||
event.preventDefault(); | ||
setIsSubmiting(true); | ||
|
||
if (!title) { | ||
handleError(onErrorMessage, ErrorMessages.EMPTY_TITLE); | ||
setIsSubmiting(false); | ||
|
||
return; | ||
} | ||
|
||
const tempTodo = { | ||
id: 0, | ||
userId: USER_ID, | ||
title: title.trim(), | ||
completed: false, | ||
}; | ||
|
||
onTempTodo(tempTodo); | ||
onErrorMessage(ErrorMessages.NONE); | ||
|
||
onAdd(tempTodo) | ||
.then(() => { | ||
setTitle(''); | ||
}) | ||
.catch(() => { | ||
handleError(onErrorMessage, ErrorMessages.ADD_FAIL); | ||
onTempTodo(null); | ||
}) | ||
.finally(() => { | ||
onTempTodo(null); | ||
setIsSubmiting(false); | ||
}); | ||
}; | ||
|
||
const handleInput = (event: React.ChangeEvent<HTMLInputElement>) => { | ||
setTitle(event.target.value.trimStart()); | ||
onErrorMessage(ErrorMessages.NONE); | ||
}; | ||
|
||
const handleToggle = () => { | ||
if (isAllCompleted) { | ||
todos.map(todo => onUpdate({ ...todo, completed: false })); | ||
} else { | ||
todos | ||
.filter(todo => !todo.completed) | ||
.map(todo => onUpdate({ ...todo, completed: true })); | ||
} | ||
}; | ||
|
||
useEffect(() => { | ||
todoInput.current?.focus(); | ||
}, [title, isSubmiting, todos.length]); | ||
|
||
return ( | ||
<header className="todoapp__header"> | ||
{!!todos.length && ( | ||
<button | ||
type="button" | ||
className={cn('todoapp__toggle-all ', { active: isAllCompleted })} | ||
data-cy="ToggleAllButton" | ||
onClick={handleToggle} | ||
/> | ||
)} | ||
|
||
<form onSubmit={handleSubmit}> | ||
<input | ||
data-cy="NewTodoField" | ||
type="text" | ||
className="todoapp__new-todo" | ||
placeholder="What needs to be done?" | ||
value={title} | ||
onChange={handleInput} | ||
autoFocus | ||
disabled={isSubmiting} | ||
ref={todoInput} | ||
/> | ||
</form> | ||
</header> | ||
); | ||
}; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.