Skip to content
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 @@ -30,4 +30,4 @@ Implement the ability to add TODOs to the `TodoList` implemented in the **Static
- 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).
- Open one more terminal and run tests with `npm test` to ensure your solution is correct.
- Replace `<your_account>` with your Github username in the [DEMO LINK](https://<your_account>.github.io/react_add-todo-form/) and add it to the PR description.
- Replace `<your_account>` with your Github username in the [DEMO LINK](https://maximtsyrulnyk.github.io/react_add-todo-form/) and add it to the PR description.
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 @@ -14,7 +14,7 @@
},
"devDependencies": {
"@cypress/react18": "^2.0.1",
"@mate-academy/scripts": "^1.8.5",
"@mate-academy/scripts": "^2.1.3",
"@mate-academy/students-ts-config": "*",
"@mate-academy/stylelint-config": "*",
"@types/node": "^20.14.10",
Expand Down
146 changes: 104 additions & 42 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,61 +1,123 @@
import './App.scss';

// import usersFromServer from './api/users';
// import todosFromServer from './api/todos';
import { useState } from 'react';

import usersFromServer from './api/users';
import todosFromServer from './api/todos';

import { TodoList } from './components/TodoList';
import { Todo } from './types/Todo';
import { User } from './types/User';

export const App = () => {
const [todos, setTodos] = useState<Todo[]>(todosFromServer);

const [title, setTitle] = useState('');
const [selectedUserId, setSelectedUserId] = useState('0');

const [titleError, setTitleError] = useState(false);
const [userError, setUserError] = useState(false);

const getUserById = (id: number): User => {
return usersFromServer.find(user => user.id === id) || usersFromServer[0];
};

const preparedTodos: Todo[] = todos.map(todo => ({
...todo,
user: getUserById(todo.userId),
}));

const generateNewTodoId = () => {
return todos.length ? Math.max(...todos.map(todoItem => todoItem.id)) + 1 : 1;
};

const resetForm = () => {
setTitle('');
setSelectedUserId('0');
setTitleError(false);
setUserError(false);
};

const handleSubmit = (event: React.FormEvent) => {
event.preventDefault();

const trimmedTitle = title.trim();
const isUserSelected = selectedUserId !== '0';

setTitleError(!trimmedTitle);
setUserError(!isUserSelected);

if (!trimmedTitle || !isUserSelected) {
return;
}

const userIdNumber = Number(selectedUserId);

const newTodo: Todo = {
id: generateNewTodoId(),
title: trimmedTitle,
completed: false,
userId: userIdNumber,
// якщо у твоєму типі Todo поле user опціональне — можна не додавати.
// Але додати корисно, щоб не було undefined у TodoInfo/UserInfo:
user: getUserById(userIdNumber),
};
Comment on lines +56 to +64
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

When creating newTodo you don't include the user object on the todo itself (you only attach users later in prepareTodos). The displayed list will have users, but the todo stored in state lacks user. If tests or later code expect each todo item in state to include a user object (as stated in the requirements: "each TODO item must have ... a user object"), consider adding user: getUserById(+userId) to newTodo so the state contains fully-prepared todos.


setTodos(currentTodos => [...currentTodos, newTodo]);
resetForm();
};

return (
<div className="App">
<h1>Add todo form</h1>

<form action="/api/todos" method="POST">
<div className="field">
<input type="text" data-cy="titleInput" />
<span className="error">Please enter a title</span>
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="titleInput">Title:</label>

<input
id="titleInput"
type="text"
data-cy="titleInput"
placeholder="Enter a title"
value={title}
onChange={event => {
setTitle(event.target.value);
setTitleError(false);
}}
/>

{titleError && <span className="error">Please enter a title</span>}
</div>

<div className="field">
<select data-cy="userSelect">
<option value="0" disabled>
Choose a user
</option>
<div>
<label htmlFor="userSelect">User:</label>

<select
id="userSelect"
data-cy="userSelect"
value={selectedUserId}
onChange={event => {
setSelectedUserId(event.target.value);
setUserError(false);
}}
>
<option value="0">Choose a user</option>

{usersFromServer.map(user => (
<option key={user.id} value={user.id}>
{user.name}
</option>
))}
</select>

<span className="error">Please choose a user</span>
{userError && <span className="error">Please choose a user</span>}
</div>

<button type="submit" data-cy="submitButton">
Add
</button>
<button type="submit">Add</button>
</form>

<section className="TodoList">
<article data-id="1" className="TodoInfo TodoInfo--completed">
<h2 className="TodoInfo__title">delectus aut autem</h2>

<a className="UserInfo" href="mailto:Sincere@april.biz">
Leanne Graham
</a>
</article>

<article data-id="15" className="TodoInfo TodoInfo--completed">
<h2 className="TodoInfo__title">delectus aut autem</h2>

<a className="UserInfo" href="mailto:Sincere@april.biz">
Leanne Graham
</a>
</article>

<article data-id="2" className="TodoInfo">
<h2 className="TodoInfo__title">
quis ut nam facilis et officia qui
</h2>

<a className="UserInfo" href="mailto:Julianne.OConner@kory.org">
Patricia Lebsack
</a>
</article>
</section>
<TodoList todos={preparedTodos} />
</div>
);
};
20 changes: 19 additions & 1 deletion src/components/TodoInfo/TodoInfo.tsx
Original file line number Diff line number Diff line change
@@ -1 +1,19 @@
export const TodoInfo = () => {};
import { UserInfo } from '../UserInfo';
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

UserInfo is imported and used with a possibly undefined prop. Either ensure todo.user is always defined before passing it, or change UserInfo to accept an optional user prop (user?: User) and handle the missing-user case inside the component to avoid a type/runtime mismatch.

import { Todo } from '../../types/Todo';

interface Props {
todo: Todo;
}

export const TodoInfo = ({ todo }: Props) => {
return (
<article
data-id={todo.id}
className={`TodoInfo${todo.completed ? ' TodoInfo--completed' : ''}`}
>
<h2 className="TodoInfo__title">{todo.title}</h2>

<UserInfo user={todo.user} />
</article>
);
};
21 changes: 20 additions & 1 deletion src/components/TodoList/TodoList.tsx
Original file line number Diff line number Diff line change
@@ -1 +1,20 @@
export const TodoList = () => {};
import { Todo } from '../../types/Todo';
import { TodoInfo } from '../TodoInfo';

type Props = {
todos?: Todo[];
};

export const TodoList = ({ todos }: Props) => {
if (!todos) {
return null;
}

return (
<section className="TodoList">
{todos.map(todo => (
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This violates CHECKLIST ITEM #4: "Don't render the component if the property that you pass to the component has null or undefined value." If todos is null/undefined, todos.map will throw. Consider adding a guard such as if (!todos) return null; or render a fallback message before calling todos.map.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This violates checklist item #4: "Don't render the component if the property that you pass to the component has null or undefined value." TodoList calls todos.map without guarding against todos being null/undefined, which can throw at runtime. Add a guard such as if (!todos) return null; before mapping (or make todos optional and handle it).

<TodoInfo key={todo.id} todo={todo} />
))}
</section>
);
};
14 changes: 13 additions & 1 deletion src/components/UserInfo/UserInfo.tsx
Original file line number Diff line number Diff line change
@@ -1 +1,13 @@
export const UserInfo = () => {};
import { User } from '../../types/User';

interface Props {
user: User;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The prop is declared as user: User (non-optional) but callers might pass undefined. This can cause runtime errors when accessing properties. Consider making the prop optional (user?: User) and guarding rendering, or ensure callers always pass a valid User. This relates to CHECKLIST ITEM #4: "Don't render the component if the property that you pass to the component has null or undefined value".

}

export const UserInfo = ({ user }: Props) => {
return (
<a className="UserInfo" href={`mailto:${user.email}`}>
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This line accesses user.email directly. If user is undefined, this will throw. If you make the prop optional, guard before rendering (e.g. if (!user) return null;), or provide a fallback value.

{user.name}
</a>
);
};
9 changes: 9 additions & 0 deletions src/types/Todo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { User } from './User';

export interface Todo {
id: number;
title: string;
completed: boolean;
userId: number;
user: User;
}
6 changes: 6 additions & 0 deletions src/types/User.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export interface User {
id: number;
name: string;
username: string;
email: string;
}
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
],
"compilerOptions": {
"sourceMap": false,
"types": ["node", "cypress"]
"types": ["node", "cypress"],
"jsx": "react-jsx"
}
}
Loading