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

Create todo app using API #767

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 9 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 @@ -41,4 +41,4 @@ Implement the ability to edit a todo title on double click:

- 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).
- Replace `<your_account>` with your Github username in the [DEMO LINK](https://<your_account>.github.io/react_todo-app-with-api/) and add it to the PR description.
- Replace `<your_account>` with your Github username in the [DEMO LINK](https://davinnchii.github.io/react_todo-app-with-api/) and add it to the PR description.
146 changes: 129 additions & 17 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,136 @@
/* 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 classNames from 'classnames';
import React, { useEffect, useMemo, useState } from 'react';
import { Todo } from './types/Todo';
import { Filters } from './utils/Filters';
import { NewTodo } from './components/NewTodo/NewTodo';
import { TodoList } from './components/TodoList/TodoList';
import { TodoFilter } from './components/TodoFilter/TodoFilter';
import {
deleteTodo,
getTodos,
} from './api/todos';
import { countTodos } from './utils/countTodos';
import {
useTodos,
} from './components/Contexts/TodosContext';
import { USER_ID } from './utils/userToken';
import {
useLoadingTodos,
} from './components/Contexts/LoadingTodosContext';
import {
useErrorMessage,
} from './components/Contexts/ErrorMessageContext';

export const App: React.FC = () => {
if (!USER_ID) {
return <UserWarning />;
}
const { todos, setTodos } = useTodos();

const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const { setLoadingTodos } = useLoadingTodos();
const {
errorMessage,
isErrorHidden,
setIsErrorHidden,
handleShowError,
} = useErrorMessage();

const [filterParam, setFilterParam] = useState(Filters.All);

const clearCompletedTodos = async () => {
const completedTodos = countTodos(todos, true).map(({ id }) => (

Choose a reason for hiding this comment

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

Better to keep all states together, all your own hooks also together, all constants together and all useEffects also together

deleteTodo(id)));

countTodos(todos, true).forEach(({ id }) => {
setLoadingTodos(prev => [...prev, id]);
});

try {
await Promise.all(completedTodos);
setTodos(prev => prev.filter(({ completed }) => !completed));
} catch {
handleShowError('Unable to delete todo');
}

setLoadingTodos([]);
};

useEffect(() => {
getTodos(USER_ID)
.then(setTodos)
.catch(() => {
handleShowError('Unable to load todos');
});
}, []);
Comment on lines +37 to +43

Choose a reason for hiding this comment

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

It's a good idea to show the loader while fetching something from a server

Choose a reason for hiding this comment

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

It's a good idea to show the loader while fetching something from a server

I still don't see a loader, when user have bad internet connection they don't know is there any todos or no


const visibleTodos = useMemo(() => {
switch (filterParam) {
case Filters.Active:
return todos.filter(({ completed }) => !completed);

case Filters.Completed:
return todos.filter(({ completed }) => completed);

case Filters.All:
return todos;

default:
return todos;

Choose a reason for hiding this comment

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

Suggested change
case Filters.All:
return todos;
default:
return todos;
case Filters.All:
default:
return todos;

}
}, [filterParam, todos]);

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">
<NewTodo onWaiting={setTempTodo} />

<section className="todoapp__main">
<TodoList todos={visibleTodos} />

{tempTodo && (

Choose a reason for hiding this comment

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

Can this tempTodo be moved to a separate component?

<div className="todo">
<label className="todo__status-label">
<input type="checkbox" className="todo__status" />
</label>

<p className="subtitle">Styles are already copied</p>
</section>
<span className="todo__title">{tempTodo.title}</span>
<button type="button" className="todo__remove">×</button>

<div className="modal overlay is-active">
<div className={'modal-background'
+ ' has-background-white-ter'}

Choose a reason for hiding this comment

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

Suggested change
<div className={'modal-background'
+ ' has-background-white-ter'}
<div className={'modal-background has-background-white-ter'}

Why do you need to concat classes like this?

Copy link
Author

Choose a reason for hiding this comment

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

Linter

/>
<div className="loader" />
</div>
</div>
)}
</section>

{!!todos?.length && (
<TodoFilter
todos={todos}
filterParam={filterParam}
onFilterChange={setFilterParam}
clearCompleted={clearCompletedTodos}
/>
)}
</div>

<div className={classNames(
'notification is-danger is-light has-text-weight-normal',
{ hidden: isErrorHidden },
)}
>
<button
type="button"
className="delete"
onClick={() => setIsErrorHidden(true)}
aria-label="Delete Button"
/>

Choose a reason for hiding this comment

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

Suggested change

{errorMessage}
<br />
</div>
</div>
);
};
27 changes: 27 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClient';

interface UpdateCompleted {
completed: boolean,
}

interface UpdateTitle {
title: string
}

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

export const addTodo = (userId: number, newTodo: Todo) => {
return client.post<Todo>(`/todos?userId=${userId}`, newTodo);
};

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

export const updateTodo = (todoId: number,
data: UpdateCompleted | UpdateTitle) => {
return client.patch<Todo>(`/todos/${todoId}`, data);
};
42 changes: 42 additions & 0 deletions src/components/Contexts/ErrorMessageContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import React, { useContext, useState } from 'react';

interface ErrorContextType {
errorMessage: string,
setErrorMessage: React.Dispatch<React.SetStateAction<string>>
isErrorHidden: boolean,
setIsErrorHidden: React.Dispatch<React.SetStateAction<boolean>>,
handleShowError: (error: string) => void,
}

export const ErrorMessageContext = React.createContext({} as ErrorContextType);

type Props = {
children: React.ReactNode,
};

export const ErrorMessageContextProvider: React.FC<Props> = ({ children }) => {
const [errorMessage, setErrorMessage] = useState('');
const [isErrorHidden, setIsErrorHidden] = useState(true);

Choose a reason for hiding this comment

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

You don't need isErrorHidden, you can check if errorMessage exists or not. An empty string is a falsy value.
https://developer.mozilla.org/en-US/docs/Glossary/Falsy
https://developer.mozilla.org/en-US/docs/Glossary/Truthy

Copy link
Author

Choose a reason for hiding this comment

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

I want my error to disappear smoothly, if I just setErrorMessage('') it will remove text and after hides the block. Which seems incorrect for me.
https://drive.google.com/file/d/1murkaSWOv1Q86OYh3rrXKQ-SDNyChk88/view?usp=sharing


const value = {
errorMessage,
setErrorMessage,
isErrorHidden,
setIsErrorHidden,
handleShowError(error: string) {
setErrorMessage(error);

setTimeout(() => {
setErrorMessage('');
}, 3000);
},
};

return (
<ErrorMessageContext.Provider value={value}>
{children}
</ErrorMessageContext.Provider>
);
};

export const useErrorMessage = () => useContext(ErrorMessageContext);
31 changes: 31 additions & 0 deletions src/components/Contexts/LoadingTodosContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import React, { useContext, useState } from 'react';

interface LoadingTodosContextType {
loadingTodos: number[],
setLoadingTodos: React.Dispatch<React.SetStateAction<number[]>>
}

export const LoadingTodosContext = React.createContext(
{} as LoadingTodosContextType,
);

type Props = {
children: React.ReactNode,
};

export const LoadingTodosContextProvider: React.FC<Props> = ({ children }) => {
const [loadingTodos, setLoadingTodos] = useState<number[]>([]);

const value = {
loadingTodos,
setLoadingTodos,
};

return (
<LoadingTodosContext.Provider value={value}>
{children}
</LoadingTodosContext.Provider>
);
};

export const useLoadingTodos = () => useContext(LoadingTodosContext);
30 changes: 30 additions & 0 deletions src/components/Contexts/TodosContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import React, { useContext, useState } from 'react';
import { Todo } from '../../types/Todo';

interface TodosContextType {
todos: Todo[],
setTodos: React.Dispatch<React.SetStateAction<Todo[]>>
}

export const TodosContext = React.createContext({} as TodosContextType);

type Props = {
children: React.ReactNode,
};

export const TodosContextProvider: React.FC<Props> = ({ children }) => {
const [todos, setTodos] = useState<Todo[]>([]);

const value = {
todos,
setTodos,
};

return (
<TodosContext.Provider value={value}>
{children}
</TodosContext.Provider>
);
};

export const useTodos = () => useContext(TodosContext);
Loading