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

Solução parcialmente adicionada #1581

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
6 changes: 3 additions & 3 deletions cypress/integration/page.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -519,7 +519,7 @@ describe('', () => {
});

// this test may be flaky
it.skip('should replace loader with a created todo', () => {
it('should replace loader with a created todo', () => {

Choose a reason for hiding this comment

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

why you change this test?

page.flushJSTimers();
todos.assertCount(6);
todos.assertNotLoading(5);
Expand Down Expand Up @@ -1515,7 +1515,7 @@ describe('', () => {
});

// It depend on your implementation
it.skip('should stay while waiting', () => {
it('should stay while waiting', () => {

Choose a reason for hiding this comment

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

why you change this test?

page.mockUpdate(257334);

todos.title(0).trigger('dblclick');
Expand Down Expand Up @@ -1694,7 +1694,7 @@ describe('', () => {
});

// this test may be unstable
it.skip('should hide loader on fail', () => {
it('should hide loader on fail', () => {

Choose a reason for hiding this comment

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

why you change this test?

// to prevent Cypress from failing the test on uncaught exception
cy.once('uncaught:exception', () => false);

Expand Down
9 changes: 5 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
},
"devDependencies": {
"@cypress/react18": "^2.0.1",
"@mate-academy/scripts": "^1.8.5",
"@mate-academy/scripts": "^1.9.12",
"@mate-academy/students-ts-config": "*",
"@mate-academy/stylelint-config": "*",
"@types/node": "^20.14.10",
Expand Down
49 changes: 34 additions & 15 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,45 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import React, { useContext, useEffect } from 'react';
import { UserWarning } from './UserWarning';

const USER_ID = 0;
import { getTodos, USER_ID } from './api/todos';
import { Header } from './components/Header';
import { TodoList } from './components/TodoList';
import { Footer } from './components/Footer';
import { ErrorNotification } from './components/ErrorNotification';
import { DispatchContext, StatesContext } from './context/Store';

export const App: React.FC = () => {
const { todos } = useContext(StatesContext);
const dispatch = useContext(DispatchContext);

useEffect(() => {
dispatch({ type: 'startUpdate' });
getTodos()
.then(todosFromServer => {
dispatch({ type: 'loadTodos', payload: todosFromServer });
})
.catch(() => {
dispatch({ type: 'showError', payload: `Unable to load todos` });
})
.finally(() => {
dispatch({ type: 'stopUpdate' });
});
}, []);

Check warning on line 26 in src/App.tsx

View workflow job for this annotation

GitHub Actions / run_linter (20.x)

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

Choose a reason for hiding this comment

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

Add dispatch as a dependency


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

<div className="todoapp__content">
<Header />
<TodoList />
{todos.length !== 0 && <Footer />}
</div>

<p className="subtitle">Styles are already copied</p>
</section>
<ErrorNotification />
</div>
);
};
34 changes: 34 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { Filter } from '../types/Filter';
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClient';

export const USER_ID = 2165;

Choose a reason for hiding this comment

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

Check this user here, you are setting the UserID (should be unique to you, Camille, not for who is using the website) to 2165.
Later on, you are passing a different number


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

export const getFilteredTodos = (filter: Filter) => {
switch (filter) {
case 'all':
return client.get<Todo[]>(`/todos?userId=${USER_ID}`);
case 'active':
return client.get<Todo[]>(`/todos?userId=${USER_ID}&completed=false`);
case 'completed':
return client.get<Todo[]>(`/todos?userId=${USER_ID}&completed=true`);
default:
return client.get<Todo[]>(`/todos?userId=${USER_ID}`);
}
};

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

export const updateTodo = (todoId: number, todo: Todo) => {
return client.patch<Todo>(`/todos/${todoId}`, todo);
};

export const addTodo = ({ userId, title, completed }: Omit<Todo, 'id'>) => {
return client.post<Todo>(`/todos`, { userId, title, completed });
};
28 changes: 28 additions & 0 deletions src/components/ErrorNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { useContext, useEffect } from 'react';
import { DispatchContext, StatesContext } from '../context/Store';
import classNames from 'classnames';

export const ErrorNotification: React.FC = () => {
const { errorMessage } = useContext(StatesContext);
const dispatch = useContext(DispatchContext);

useEffect(() => {
if (errorMessage) {
setTimeout(() => dispatch({ type: 'showError', payload: null }), 3000);
}
});

return (
<div
data-cy="ErrorNotification"
className={classNames(
'notification is-danger is-light has-text-weight-normal',
{ hidden: !errorMessage },
)}
>
<button data-cy="HideErrorButton" type="button" className="delete" />
{/* show only one message at a time */}
{errorMessage}
</div>
);
};
87 changes: 87 additions & 0 deletions src/components/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { useContext } from 'react';
import { DispatchContext, StatesContext } from '../context/Store';
import { Filter } from '../types/Filter';
import classNames from 'classnames';
import { deleteTodo } from '../api/todos';

export const Footer: React.FC = () => {
const { todos, filter } = useContext(StatesContext);
const dispatch = useContext(DispatchContext);
const todosLeft = todos.filter(t => !t.completed);

function handleOnFilterClick(selectedFilter: Filter) {
dispatch({ type: 'setFilter', payload: selectedFilter });
}

const handleOnClearClick = () => {
const completedTodos = todos.filter(t => t.completed);

Promise.allSettled(
completedTodos.map(todo => deleteTodo(todo.id).then(() => todo.id)),
).then(results => {
if (results.some(res => res.status === 'rejected')) {
dispatch({ type: 'showError', payload: 'Unable to delete a todo' });
}

return results
.filter(
(res): res is PromiseFulfilledResult<number> =>
res.status === 'fulfilled',
)
.map(res => dispatch({ type: 'deleteTodo', payload: res.value }));
});
};

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

<nav className="filter" data-cy="Filter">
<a
href="#/"
className={classNames('filter__link', {
selected: filter === 'all',
})}
data-cy="FilterLinkAll"
onClick={() => handleOnFilterClick(Filter.all)}
>
All
</a>

<a
href="#/active"
className={classNames('filter__link', {
selected: filter === 'active',
})}
data-cy="FilterLinkActive"
onClick={() => handleOnFilterClick(Filter.active)}
>
Active
</a>

<a
href="#/completed"
className={classNames('filter__link', {
selected: filter === 'completed',
})}
data-cy="FilterLinkCompleted"
onClick={() => handleOnFilterClick(Filter.completed)}
>
Completed
</a>
</nav>

<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
onClick={() => handleOnClearClick()}
disabled={todos.length === 0 || !todos.some(t => t.completed)}
>
Clear completed
</button>
</footer>
);
};
47 changes: 47 additions & 0 deletions src/components/Header.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { useContext } from 'react';
import { NewTodoField } from './NewTodoField';
import { DispatchContext, StatesContext } from '../context/Store';
import { updateTodo } from '../api/todos';
import classNames from 'classnames';

export const Header: React.FC = () => {
const dispatch = useContext(DispatchContext);
const { todos } = useContext(StatesContext);
const handleOnToggleAll = () => {
const toggledTodos = todos.every(todo => todo.completed)
? todos
: todos.filter(t => !t.completed);

toggledTodos.map(todo => {
dispatch({ type: 'startUpdate' });
updateTodo(todo.id, { ...todo, completed: !todo.completed })
.then(newTodo => {
dispatch({ type: 'selectTodo', payload: newTodo.id });
dispatch({ type: 'updateTodo', payload: newTodo });
})
.catch(() => {
dispatch({ type: 'showError', payload: 'Unable to update a todo' });
})
.finally(() => {
dispatch({ type: 'stopUpdate' });
});
});
};

return (
<header className="todoapp__header">
{todos.length !== 0 && (
<button
type="button"
className={classNames('todoapp__toggle-all', {
active: todos.every(t => t.completed),
})}
data-cy="ToggleAllButton"
onClick={handleOnToggleAll}
/>
)}

<NewTodoField />
</header>
);
};
63 changes: 63 additions & 0 deletions src/components/NewTodoField.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { useContext, useEffect, useRef, useState } from 'react';
import { DispatchContext, StatesContext } from '../context/Store';
import { addTodo } from '../api/todos';

export const NewTodoField: React.FC = () => {
const dispatch = useContext(DispatchContext);
const { isUpdating, todos, errorMessage } = useContext(StatesContext);
const [title, setTitle] = useState('');
const handleOnChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setTitle(event.target.value);
};

const inputRef = useRef<HTMLInputElement | null>(null);

const handleOnSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
dispatch({ type: 'startUpdate' });
if (!title.trim()) {
dispatch({
type: 'showError',
payload: 'Title should not be empty',
});
dispatch({ type: 'stopUpdate' });
} else {
dispatch({
type: 'addTempTodo',
payload: { userId: 962, id: 0, title: title.trim(), completed: false },
});
addTodo({ userId: 962, title: title.trim(), completed: false })

Choose a reason for hiding this comment

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

Here you are sending to the API an Todo that belongs to the UserId 962, which is a different number.
If the numbers mismatch, you are probably trying to load your todos in the GET method, but saving them to another user, so they won't be found by you.

.then(newTodo => {
dispatch({ type: 'addTodo', payload: newTodo });
setTitle('');
})
.catch(() => {
dispatch({ type: 'showError', payload: 'Unable to add a todo' });
})
.finally(() => {
inputRef.current?.focus();
dispatch({ type: 'removeTempTodo' });
dispatch({ type: 'stopUpdate' });
});
}
};

useEffect(() => {
inputRef.current?.focus();
}, [todos, errorMessage]);

return (
<form onSubmit={handleOnSubmit}>
<input
data-cy="NewTodoField"
type="text"
className="todoapp__new-todo"
placeholder="What needs to be done?"
value={title}
onChange={handleOnChange}
disabled={isUpdating}
ref={inputRef}
/>
</form>
);
};
Loading
Loading