/
TodoPrivateList.js
102 lines (88 loc) · 2.37 KB
/
TodoPrivateList.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import React, { Fragment, useState } from "react";
import { useQuery, useMutation, gql } from "@apollo/client";
import TodoItem from "./TodoItem";
import TodoFilters from "./TodoFilters";
const GET_MY_TODOS = gql`
query getMyTodos {
todos(
where: { is_public: { _eq: false } }
order_by: { created_at: desc }
) {
id
title
created_at
is_completed
}
}
`;
// Remove all the todos that are completed
const CLEAR_COMPLETED = gql`
mutation clearCompleted {
delete_todos(
where: { is_completed: { _eq: true }, is_public: { _eq: false } }
) {
affected_rows
}
}
`;
const TodoPrivateList = props => {
const [state, setState] = useState({
filter: "all",
clearInProgress: false
});
const filterResults = filter => {
setState({
...state,
filter: filter
});
};
const [clearCompletedTodos] = useMutation(CLEAR_COMPLETED);
const clearCompleted = () => {
clearCompletedTodos({
optimisticResponse: true,
update: (cache, { data }) => {
const existingTodos = cache.readQuery({ query: GET_MY_TODOS });
const newTodos = existingTodos.todos.filter(t => !t.is_completed);
cache.writeQuery({ query: GET_MY_TODOS, data: { todos: newTodos } });
}
});
};
const { todos } = props;
let filteredTodos = todos;
if (state.filter === "active") {
filteredTodos = todos.filter(todo => todo.is_completed !== true);
} else if (state.filter === "completed") {
filteredTodos = todos.filter(todo => todo.is_completed === true);
}
const todoList = [];
filteredTodos.forEach((todo, index) => {
todoList.push(<TodoItem key={index} index={index} todo={todo} />);
});
return (
<Fragment>
<div className="todoListWrapper">
<ul>{todoList}</ul>
</div>
<TodoFilters
todos={filteredTodos}
currentFilter={state.filter}
filterResultsFn={filterResults}
clearCompletedFn={clearCompleted}
clearInProgress={state.clearInProgress}
/>
</Fragment>
);
};
const TodoPrivateListQuery = () => {
const { loading, error, data } = useQuery(GET_MY_TODOS);
if (loading) {
return <div>Loading...</div>;
}
if (error) {
console.error(error);
return <div>Error!</div>;
}
return <TodoPrivateList todos={data.todos} />;
};
export default TodoPrivateListQuery;
export { GET_MY_TODOS };