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

added solution #2699

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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,4 @@ loaded and show them using `TodoList` (check the code in the `api.ts`);
- 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_dynamic-list-of-todos/) and add it to the PR description.
- Replace `<your_account>` with your Github username in the [DEMO LINK](https://alechsva.github.io/react_dynamic-list-of-todos/) and add it to the PR description.
37 changes: 32 additions & 5 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable max-len */
import React from 'react';
import React, { useEffect, useState } from 'react';
import 'bulma/css/bulma.css';
import '@fortawesome/fontawesome-free/css/all.css';

Expand All @@ -8,7 +8,25 @@ import { TodoFilter } from './components/TodoFilter';
import { TodoModal } from './components/TodoModal';
import { Loader } from './components/Loader';

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

export const App: React.FC = () => {
const [loading, setLoading] = useState(true);
const [currentTodo, setCurrentTodo] = useState<Todo | null>(null);
const [todos, setTodos] = useState<Todo[]>([]);
const [allTodos, setAllTodos] = useState<Todo[]>();

Choose a reason for hiding this comment

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

Consider initializing allTodos with an empty array [] instead of undefined. This will prevent potential issues when accessing allTodos before it is set.


useEffect(() => {
if (!allTodos) {
getTodos().then(setAllTodos, setTodos);

Choose a reason for hiding this comment

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

The getTodos function is being used incorrectly. The then method should be used to set allTodos and handle any errors separately. Consider using .then(setAllTodos).catch(errorHandler) to handle errors properly.

}

if (todos.length > 0) {
setLoading(false);
}
}, [allTodos, todos]);

return (
<>
<div className="section">
Expand All @@ -17,18 +35,27 @@ export const App: React.FC = () => {
<h1 className="title">Todos:</h1>

<div className="block">
<TodoFilter />
<TodoFilter allTodos={allTodos} setTodos={setTodos} />
</div>

<div className="block">
<Loader />
<TodoList />
{loading ? (
<Loader />
) : (
<TodoList
todos={todos}
currentTodo={currentTodo}
setCurrentTodo={setCurrentTodo}
/>
)}
</div>
</div>
</div>
</div>

<TodoModal />
{currentTodo && (
<TodoModal currentTodo={currentTodo} setCurrentTodo={setCurrentTodo} />
)}
</>
);
};
4 changes: 0 additions & 4 deletions src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import { User } from './types/User';
const BASE_URL =
'https://mate-academy.github.io/react_dynamic-list-of-todos/api';

// This function creates a promise
// that is resolved after a given delay
function wait(delay: number): Promise<void> {
return new Promise(resolve => {
setTimeout(resolve, delay);
Expand All @@ -17,12 +15,10 @@ function get<T>(url: string): Promise<T> {
// eslint-disable-next-line prefer-template
const fullURL = BASE_URL + url + '.json';

// we add some delay to see how the loader works
return wait(300)
.then(() => fetch(fullURL))
.then(res => res.json());
}

export const getTodos = () => get<Todo[]>('/todos');

export const getUser = (userId: number) => get<User>(`/users/${userId}`);
7 changes: 7 additions & 0 deletions src/components/Option/Option.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
interface Props {
optionValue: string;
}

export const Option: React.FC<Props> = ({ optionValue }) => {
return <option value={optionValue.toLowerCase()}>{optionValue}</option>;
};
1 change: 1 addition & 0 deletions src/components/Option/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './Option';
124 changes: 94 additions & 30 deletions src/components/TodoFilter/TodoFilter.tsx
Original file line number Diff line number Diff line change
@@ -1,30 +1,94 @@
export const TodoFilter = () => (
<form className="field has-addons">
<p className="control">
<span className="select">
<select data-cy="statusSelect">
<option value="all">All</option>
<option value="active">Active</option>
<option value="completed">Completed</option>
</select>
</span>
</p>

<p className="control is-expanded has-icons-left has-icons-right">
<input
data-cy="searchInput"
type="text"
className="input"
placeholder="Search..."
/>
<span className="icon is-left">
<i className="fas fa-magnifying-glass" />
</span>

<span className="icon is-right" style={{ pointerEvents: 'all' }}>
{/* eslint-disable-next-line jsx-a11y/control-has-associated-label */}
<button data-cy="clearSearchButton" type="button" className="delete" />
</span>
</p>
</form>
);
import { Todo } from '../../types/Todo';
import { useState, useEffect } from 'react';
import { Option } from '../Option';

interface Props {
allTodos?: Todo[];
setTodos: (value: Todo[]) => void;
}

type FilterType = 'all' | 'active' | 'completed';

export const TodoFilter: React.FC<Props> = ({ allTodos, setTodos }) => {
const [inputSearch, setInputSearch] = useState<string>('');
const [close, setClose] = useState(false);
const [filter, setFilter] = useState<FilterType>('all');

Choose a reason for hiding this comment

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

The close state is redundant. You can determine if the input is empty directly from inputSearch. Consider removing close and using !!inputSearch where needed.


useEffect(() => {
if (allTodos) {
let newTodos = [...allTodos];

if (filter === 'active') {
newTodos = allTodos?.filter(todo => !todo.completed);
} else if (filter === 'completed') {

Choose a reason for hiding this comment

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

The use of optional chaining allTodos?.filter is unnecessary here because allTodos is already checked for existence. You can safely use allTodos.filter.

newTodos = allTodos?.filter(todo => todo.completed);
} else {

Choose a reason for hiding this comment

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

The use of optional chaining allTodos?.filter is unnecessary here because allTodos is already checked for existence. You can safely use allTodos.filter.

newTodos = allTodos;
}

if (inputSearch.trim()) {
newTodos = newTodos.filter(todo =>
todo.title.toLowerCase().includes(inputSearch.toLowerCase()),
);
}

setTodos(newTodos);
}
}, [inputSearch, allTodos, filter, setTodos]);

const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setInputSearch(event.target.value);
setClose(!!event.target.value);
};

const handleCloseClick = () => {
setInputSearch('');
setClose(false);
};

const handleSelectChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
setFilter(event.target.value as FilterType);
};

return (
<form className="field has-addons">
<p className="control">
<span className="select">
<select
data-cy="statusSelect"
onChange={handleSelectChange}
value={filter}
>
{['All', 'Active', 'Completed'].map(item => (
<Option optionValue={item} key={item} />
))}
</select>
</span>
</p>

<p className="control is-expanded has-icons-left has-icons-right">
<input
data-cy="searchInput"
type="text"
className="input"
placeholder="Search..."
value={inputSearch}
onChange={handleInputChange}
/>
<span className="icon is-left">
<i className="fas fa-magnifying-glass" />
</span>
{close && (
<span className="icon is-right" style={{ pointerEvents: 'all' }}>
<button
data-cy="clearSearchButton"
type="button"
className="delete"
onClick={handleCloseClick}
/>
</span>
)}
</p>
</form>
);
};
62 changes: 62 additions & 0 deletions src/components/TodoItem/TodoItem.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import classNames from 'classnames';
import { Todo } from '../../types/Todo';

interface Props {
todo: Todo;
currentTodo: Todo | null;
setCurrentTodo: (todo: Todo) => void;
}

export const TodoItem: React.FC<Props> = ({
todo,
currentTodo,
setCurrentTodo,
}) => {
const handleClick = () => {
setCurrentTodo(todo);
};

const { title, id, completed } = todo;

return (
<tr data-cy="todo" className="">
<td className="is-vcentered">{id}</td>
{completed ? (
<td className="is-vcentered">
<span className="icon" data-cy="iconCompleted">
<i className="fas fa-check" />
</span>
</td>
) : (
<td className="is-vcentered" />
)}
<td className="is-vcentered is-expanded">
<p
className={classNames({
'has-text-danger': !completed,
'has-text-success': completed,
})}
>
{title}
</p>
</td>
<td className="has-text-right is-vcentered">
<button
data-cy="selectButton"
className="button"
type="button"
onClick={handleClick}
>
<span className="icon">
<i
className={classNames('far', {
'fa-eye': currentTodo?.id !== id,
'fa-eye-slash': currentTodo?.id === id,
})}
/>
</span>
</button>
</td>
</tr>
);
};
1 change: 1 addition & 0 deletions src/components/TodoItem/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './TodoItem';
Loading
Loading