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

implement update logic, failed from 2 to 5 tests, every time different. Work in progress #806

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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
65 changes: 52 additions & 13 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,63 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import { useContext, useEffect } from 'react';

import { UserWarning } from './UserWarning';
import { Footer } from './components/Footer';
import { Header } from './components/Header';
import { ErrorNotification } from './components/ErrorNotification';

import { getTodos } from './api/todos';
import { USER_ID } from './utils/variables';
import { TodoList } from './components/TodoList';
import { TodosContext } from './components/TodosContext';
import { ErrorMessage } from './types/ErrorMessage';

const USER_ID = 0;
export const App = () => {
const {
todos,
setTodos,
setFilteredTodos,
setAlarm,
} = useContext(TodosContext);

useEffect(() => {
if (USER_ID) {
getTodos(USER_ID)
.then(todosFromServer => {
setTodos(todosFromServer);
setFilteredTodos(todosFromServer);
setAlarm(ErrorMessage.Default);
})
.catch(errorMessage => {
// eslint-disable-next-line no-console
console.log(errorMessage);
setAlarm(ErrorMessage.isLoadTodoError);
setTodos([]);
});
}
}, [USER_ID]);

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

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

{!!todos.length && (
<>
<TodoList />

<Footer />
</>
)}
</div>

<ErrorNotification />
</div>
);
};
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 createTodo = ({ title, userId, completed }: Omit<Todo, 'id'>) => {
return client.post<Todo>('/todos', { title, userId, completed });
};

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

export const updateTodo = (todo: Todo) => {
return client.patch(`/todos/${todo.id}`, todo);
};
45 changes: 45 additions & 0 deletions src/components/ErrorNotification/ErrorNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/* eslint-disable jsx-a11y/control-has-associated-label */

Choose a reason for hiding this comment

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

Try to rewrite the code so that it is not necessary to disable the linter

import { useContext, useEffect, useRef } from 'react';
import cn from 'classnames';
import { TodosContext } from '../TodosContext';
import { ErrorMessage } from '../../types/ErrorMessage';

export const ErrorNotification = () => {
const {
alarm,
setAlarm,
} = useContext(TodosContext);

const timerId = useRef<number>(0);

Choose a reason for hiding this comment

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

Suggested change
const timerId = useRef<number>(0);
const timerIdRef = useRef<number>(0);


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

timerId.current = window.setTimeout(() => {
setAlarm(ErrorMessage.Default);
}, 3000);
}, [alarm]);

Choose a reason for hiding this comment

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


return (
<div
data-cy="ErrorNotification"
className={cn(
'notification',
'is-light',
'is-danger',
'has-text-weight-normal',
{ hidden: !alarm },
)}
>
<button
data-cy="HideErrorButton"
type="button"
className="delete"
onClick={() => setAlarm(ErrorMessage.Default)}
/>
{alarm}
</div>
);
};
1 change: 1 addition & 0 deletions src/components/ErrorNotification/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './ErrorNotification';
78 changes: 78 additions & 0 deletions src/components/Footer/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/* eslint-disable jsx-a11y/control-has-associated-label */

Choose a reason for hiding this comment

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

Try to rewrite the code so that it is not necessary to disable the linter

import { useContext, useEffect, useState } from 'react';
import cn from 'classnames';
import { TodosContext } from '../TodosContext';
import { FilterOption, OPTIONS, filterTodos } from '../../utils/variables';

export const Footer = () => {
const {
todos,
setFilteredTodos,
handleRemoveTodo,
isTodoChange,
changingItems,
} = useContext(TodosContext);
const [selectedOption, setSelectedOption] = useState(FilterOption.Default);
const [hasCompleted, setHasCompleted] = useState(false);

useEffect(() => {
setSelectedOption(FilterOption.All);
}, []);

useEffect(() => {
setFilteredTodos(filterTodos(selectedOption, todos));
setHasCompleted(todos.some(todo => todo.completed));
}, [selectedOption, isTodoChange, changingItems]);

const handleFilterTodos = (option: FilterOption) => {
setSelectedOption(option);
};

const removeAllCompletedTodos = () => {
const completedTodos = filterTodos(FilterOption.Completed, todos);

completedTodos.forEach(todo => handleRemoveTodo(todo));
setHasCompleted(false);
};

const counterTodos = todos.filter(todo => !todo.completed).length;

return (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{`${counterTodos} items left`}

Choose a reason for hiding this comment

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

When there is only one todo there should not be plural in the message.

</span>

<nav className="filter" data-cy="Filter">
{OPTIONS.map(option => {
const isSelected = selectedOption === option;

return (
<a
key={option}
href={`#/${option.toLowerCase()}`}
data-cy={`FilterLink${option}`}
className={cn(
'filter__link',
{ selected: isSelected },
)}
onClick={() => handleFilterTodos(option)}
>
{option}
</a>
);
})}
</nav>

<button
data-cy="ClearCompletedButton"
type="button"
className="todoapp__clear-completed"
disabled={!hasCompleted}
onClick={removeAllCompletedTodos}
>
Clear completed
</button>
</footer>
);
};
1 change: 1 addition & 0 deletions src/components/Footer/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './Footer';
152 changes: 152 additions & 0 deletions src/components/Header/Header.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
/* eslint-disable jsx-a11y/control-has-associated-label */

Choose a reason for hiding this comment

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

Try to rewrite the code so that it is not necessary to disable the linter

import React, {
useContext,
useEffect,
useRef,
useState,
} from 'react';

import cn from 'classnames';

import { Todo } from '../../types/Todo';
import { createTodo, updateTodo } from '../../api/todos';
import { USER_ID } from '../../utils/variables';
import { TodosContext } from '../TodosContext';
import { ErrorMessage } from '../../types/ErrorMessage';

export const Header = () => {
const {
todos,
setTodos,
setAlarm,
setTempTodo,
isTodoChange,
setIsTodoChange,
setChangingItems,
} = useContext(TodosContext);

const titleInput = useRef<HTMLInputElement>(null);

Choose a reason for hiding this comment

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

Suggested change
const titleInput = useRef<HTMLInputElement>(null);
const titleInputRef = useRef<HTMLInputElement>(null);


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

const [inputValue, setInputValue] = useState('');

const isAllCompletedTodos = todos.every(todo => todo.completed);

Choose a reason for hiding this comment

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

Suggested change
const isAllCompletedTodos = todos.every(todo => todo.completed);
const isAllTodosCompleted = todos.every(todo => todo.completed);


const addTodo = ({ title, userId, completed }: Omit<Todo, 'id'>) => {
createTodo({ title, userId, completed })
.then(newTodo => {
setTodos(currentTodos => [...currentTodos, newTodo]);
setTempTodo(null);
setInputValue('');
setChangingItems([]);
})
.catch(() => {
setAlarm(ErrorMessage.isUnableAddTodo);
setTempTodo(null);
})
.finally(() => {
setIsTodoChange(false);
});
};

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

const trimmedInputValue = inputValue.trim();

if (!trimmedInputValue) {
setAlarm(ErrorMessage.isTitleEmpty);
setInputValue('');

return;
}

setChangingItems(current => [...current, 0]);
setIsTodoChange(true);

const newTodo = {
title: trimmedInputValue,
userId: USER_ID,
completed: false,
};

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

const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setInputValue(event.target.value);
setAlarm(ErrorMessage.Default);
};

const updateToggleTodoCompleted = (todo: Todo, val: boolean) => {
const newTodo = {
...todo,
completed: val,
};

setIsTodoChange(true);
setChangingItems(current => [...current, todo.id]);
updateTodo(newTodo)
.then(() => {
setIsTodoChange(false);
setTodos(currentTodos => currentTodos
.map(currTodo => {
return currTodo.id !== newTodo.id
? currTodo
: newTodo;
}));
})
.catch(() => setAlarm(ErrorMessage.isUnableUpdateTodo))
.finally(() => {
setChangingItems([]);
});
};

const handleAllCompletedTodos = () => {
const notCompletedTodos = todos.filter(todo => !todo.completed);

if (notCompletedTodos.length > 0) {

Choose a reason for hiding this comment

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

Suggested change
if (notCompletedTodos.length > 0) {
if (!!notCompletedTodos.length) {

notCompletedTodos.forEach(todo => updateToggleTodoCompleted(todo, true));
} else {
todos.forEach(todo => updateToggleTodoCompleted(todo, false));
}
};

return (
<header className="todoapp__header">
{ !!todos.length && (

Choose a reason for hiding this comment

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

Suggested change
{ !!todos.length && (
{!!todos.length && (

<button
type="button"
data-cy="ToggleAllButton"
className={cn(
'todoapp__toggle-all',
{ active: isAllCompletedTodos },
)}
onClick={handleAllCompletedTodos}
/>
)}

<form onSubmit={handleSubmitForm}>
<input
data-cy="NewTodoField"
value={inputValue}
ref={titleInput}
type="text"
className="todoapp__new-todo"
placeholder="What needs to be done?"
onChange={handleInputChange}
disabled={isTodoChange}
/>
</form>
</header>
);
};
1 change: 1 addition & 0 deletions src/components/Header/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './Header';
Loading