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 task solution #1518

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
166 changes: 147 additions & 19 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,154 @@
/* 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, { FormEvent, useMemo, useState, useEffect } from 'react';
import cn from 'classnames';
import { Todo } from './types/Todo';
import { Header } from './components/Header';
import { TodoList } from './components/TodoList';
import { getTodos } from './api/todos';
import { FooterPart } from './components/Footer';
import { ErrorMessage } from './components/errorsMessage';
import { Status } from './components/status';
import { createTodos, USER_ID } from './api/todos';

export const App: React.FC = () => {
if (!USER_ID) {
return <UserWarning />;
const [todos, setTodos] = useState<Todo[]>([]);

const [todoTemplate, setTodoTempalte] = useState<Todo | null>(null);
const [error, setError] = useState<ErrorMessage | ''>('');
const [status, setStatus] = useState<Status>(Status.All);
const [valueTitle, setValue] = useState<string>('');
const [disableInput, setDisableInput] = useState(false);

const uploadingTodos = useMemo(() => {
setError(ErrorMessage.noError);

getTodos()
.then(setTodos)
.catch(() => {
setError(ErrorMessage.loadError);
setTimeout(() => {
setError(ErrorMessage.noError);
}, 3000);
})
.finally();
}, []);

Choose a reason for hiding this comment

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

Suggested change
.finally();


function deleteError() {
setError(ErrorMessage.noError);

Choose a reason for hiding this comment

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

It is important to follow the same way of creating functions everywhere

Suggested change
function deleteError() {
const deleteError = () => {

}

const addPost = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
const getTrim = valueTitle.trim();

if (!getTrim) {
setValue('');
setError(ErrorMessage.titleError);
setTimeout(() => setError(ErrorMessage.noError), 3000);

return false;
}

setDisableInput(true);
setTodoTempalte({
id: 0,
completed: false,
title: getTrim,
userId: USER_ID,
});
todos.filter((todo: Todo) => !todo.completed);
setTodos(currentTodos => [
...currentTodos,
{ id: 0, completed: false, title: getTrim, userId: USER_ID },
]);

return createTodos({ completed: false, title: getTrim, userId: USER_ID })
.then(newTodo => {
setTodos(currentTodos => [...currentTodos, newTodo]);
setValue('');
})
.catch(() => {
setError(ErrorMessage.addError);
setTimeout(() => {
setError(ErrorMessage.noError);
}, 3000);
})
.finally(() => {
setTodos(currentTodos => currentTodos.filter(todo => todo.id !== 0));
setTodoTempalte(null);
setDisableInput(false);
});
};

const filterTodosByStatus = () => {
switch (status) {
case Status.Active:
return todos.filter((todo: Todo) => !todo.completed);
case Status.Completed:
return todos.filter((todo: Todo) => todo.completed);
default:
return todos;
}
};

const filteredTodos = filterTodosByStatus();

useEffect(() => uploadingTodos);

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
setTodos={setTodos}
setIsInputLoading={todos.length}
posts={todos}
setTodoTemplate={setTodoTempalte}
addPost={addPost}
valueTitle={valueTitle}
setValue={setValue}
disableInput={disableInput}
setErrorMessage={setError}
/>
<TodoList
posts={filteredTodos}
setTodos={setTodos}
error={error}
setErrorMessage={setError}
todoTemplate={todoTemplate}
/>
{todos.length > 0 && (
<FooterPart
posts={todos}
filterStatus={setStatus}
status={status}
setTodos={setTodos}
todoTemplate={todoTemplate}
setErrorMessage={setError}
/>
)}
</div>

<div
data-cy="ErrorNotification"
className={cn(
'notification',
'is-danger',
'is-light',
'has-text-weight-normal',
{
hidden: !error,
},
)}
>
<button
data-cy="HideErrorButton"
onClick={deleteError}
type="button"
className="delete"
/>
{error}
</div>
</div>
);
};
31 changes: 31 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClient';

export const USER_ID = 1843;

// interface UpdateTodo {
// id: Todo['id'];
// objectData: Todo;
// }
Comment on lines +6 to +9

Choose a reason for hiding this comment

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

Remove all comments

Suggested change
// interface UpdateTodo {
// id: Todo['id'];
// objectData: Todo;
// }


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

export const createTodos = (obj: Omit<Todo, 'id'>) => {
return client.post<Todo[]>('/todos', obj);
};

export const updateTodos = ({
id,
userId,
title,
completed,
}: Todo): Promise<Todo> => {
return client.patch(`/todos/${id}`, { userId, title, completed });
};

export const deleteTodos = (id: number) => {
return client.delete(`/todos/${id}`);
};
// Add more methods here
80 changes: 80 additions & 0 deletions src/components/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import React from 'react';
import { Todo } from '../types/Todo';
import { Status } from './status';
import { deleteTodos } from '../api/todos';
import { ErrorMessage } from './errorsMessage';
import cn from 'classnames';

interface Props {
posts: Todo[];
filterStatus: (status: Status) => void;
status: Status;
setErrorMessage: (errorMessage: ErrorMessage) => void;
setTodos: React.Dispatch<React.SetStateAction<Todo[]>>;
todoTemplate: Todo | null;
}

export const FooterPart: React.FC<Props> = ({
posts,
filterStatus,
status,
setTodos,
todoTemplate,
setErrorMessage,
}) => {
const count = posts.filter(
value => !value.completed && todoTemplate != value && value.id != 0,
).length;
const deleteComplete = () => {
posts.map(value => {
if (value.completed) {
deleteTodos(value.id)
.then(() => {
setTodos(currentTodos =>
currentTodos.filter(todo => todo.id !== value.id),
);
})
.catch(() => {
setErrorMessage(ErrorMessage.deleteError);
setTimeout(() => {
setErrorMessage(ErrorMessage.noError);
}, 3000);
});
}
});
};

return (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{count} items left
</span>
<nav className="filter" data-cy="Filter">
{Object.values(Status).map(val => (
<a
key={val}
href={`#/${val.toLowerCase()}`}
className={cn('filter__link', {
selected: status === val,
})}
data-cy={`FilterLink${val}`}
onClick={() => filterStatus(val)}
>
{val}
</a>
))}
</nav>

{/* this button should be disabled if there are no completed todos */}
<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
disabled={!posts.find(element => element.completed)}
onClick={deleteComplete}
>
Clear completed
</button>
</footer>
);
};
102 changes: 102 additions & 0 deletions src/components/Header.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import cn from 'classnames';
import React, { ChangeEvent, FormEvent, useEffect, useRef } from 'react';
import { updateTodos, USER_ID } from '../api/todos';
import { Todo } from '../types/Todo';
import { ErrorMessage } from './errorsMessage';

type Props = {
setTodos: React.Dispatch<React.SetStateAction<Todo[]>>;
setErrorMessage: (errorMessage: ErrorMessage) => void;
posts: Todo[];
disableInput?: boolean;
setIsInputLoading: number;
setTodoTemplate: React.Dispatch<React.SetStateAction<Todo | null>>;
valueTitle: string;
setValue: React.Dispatch<React.SetStateAction<string>>;
addPost: (event: FormEvent<HTMLFormElement>) => void;
};

export const Header: React.FC<Props> = ({
setTodos,
setErrorMessage,
posts,
setIsInputLoading,
addPost,
valueTitle,
setValue,
disableInput,
}) => {
const fieldFocus = useRef<HTMLInputElement>(null);

useEffect(() => {
if (fieldFocus.current) {
fieldFocus.current.focus();
}
}, [setIsInputLoading, posts]);
const areAllCompleted = posts.every((todo: Todo) => todo.completed);
Comment on lines +35 to +36

Choose a reason for hiding this comment

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

Suggested change
}, [setIsInputLoading, posts]);
const areAllCompleted = posts.every((todo: Todo) => todo.completed);
}, [setIsInputLoading, posts]);
const areAllCompleted = posts.every((todo: Todo) => todo.completed);


const setCompleted = () => {
let flag = true;

if (areAllCompleted) {
flag = false;
}

posts.map(post => {
const id = post.id;

if (post.completed != flag) {
updateTodos({
id: id,
userId: USER_ID,
title: post.title,
completed: flag,
})
.then(respone => {
setTodos(prevTodos =>
prevTodos.map((item: Todo) =>
item.id === respone.id ? respone : item,
),
);
})
.catch(() => {
setErrorMessage(ErrorMessage.updateError);
setTimeout(() => {
setErrorMessage(ErrorMessage.noError);
}, 3000);
});
}
});
};

const onTextChange = (e: ChangeEvent<HTMLInputElement>) => {
setValue(e.target.value);
};

return (
<header className="todoapp__header">
{posts.length !== 0 && (
<button
type="button"
data-cy="ToggleAllButton"
className={cn('todoapp__toggle-all', {
active: areAllCompleted,
})}
onClick={setCompleted}
/>
)}
<form onSubmit={event => addPost(event)}>
<input
ref={fieldFocus}
data-cy="NewTodoField"
type="text"
onChange={onTextChange}
value={valueTitle}
className="todoapp__new-todo"
placeholder="What needs to be done?"
disabled={disableInput}
/>
</form>
</header>
);
};
Loading
Loading