Skip to content
This repository was archived by the owner on Jul 16, 2024. It is now read-only.

Commit 876b5af

Browse files
author
Paul Korzhyk
committed
Use mutation to update properties of the todo objects
1 parent e954805 commit 876b5af

File tree

1 file changed

+46
-25
lines changed

1 file changed

+46
-25
lines changed

src/TodoModel.js

Lines changed: 46 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
import Utils from './Utils'
2-
31
import * as dgraph from 'dgraph-js-http'
42

53
export default class TodoModel {
@@ -13,6 +11,10 @@ export default class TodoModel {
1311

1412
async fetchAndInform() {
1513
this.todos = await this.fetchTodos()
14+
15+
this.todos.forEach(Object.freeze)
16+
Object.freeze(this.todos)
17+
1618
this.inform()
1719
}
1820

@@ -59,26 +61,37 @@ export default class TodoModel {
5961
}
6062
}
6163

62-
toggleAll = checked => {
63-
// Note: it's usually better to use immutable data structures since they're
64-
// easier to reason about and React works very well with them. That's why
65-
// we use map() and filter() everywhere instead of mutating the array or
66-
// todo items themselves.
67-
this.todos = this.todos.map(function (todo) {
68-
return Object.assign({}, todo, {completed: checked});
69-
})
64+
async toggleAll(completed) {
65+
try {
66+
const toggleJson = this.todos
67+
.map(({ uid }) => ({ uid, completed }))
7068

71-
this.inform()
72-
}
69+
await this.dgraph.newTxn().mutate({
70+
setJson: toggleJson,
71+
commitNow: true,
72+
})
73+
} catch (error) {
74+
console.error('Network error', error)
75+
} finally {
76+
this.fetchAndInform()
77+
}
7378

74-
toggle = todoToToggle => {
75-
this.todos = this.todos.map(function (todo) {
76-
return todo !== todoToToggle ?
77-
todo :
78-
Object.assign({}, todo, {completed: !todo.completed});
79-
})
79+
}
8080

81-
this.inform()
81+
async toggle(todoToToggle) {
82+
try {
83+
await this.dgraph.newTxn().mutate({
84+
setJson: {
85+
uid: todoToToggle.uid,
86+
completed: !todoToToggle.completed,
87+
},
88+
commitNow: true,
89+
})
90+
} catch (error) {
91+
console.error('Network error', error)
92+
} finally {
93+
this.fetchAndInform()
94+
}
8295
}
8396

8497
async destroy(todo) {
@@ -97,12 +110,20 @@ export default class TodoModel {
97110
}
98111
}
99112

100-
save = (todoToSave, text) => {
101-
this.todos = this.todos.map(function (todo) {
102-
return todo !== todoToSave ? todo : Object.assign({}, todo, {title: text})
103-
})
104-
105-
this.inform()
113+
async save(todoToSave, newTitle) {
114+
try {
115+
await this.dgraph.newTxn().mutate({
116+
setJson: {
117+
uid: todoToSave.uid,
118+
title: newTitle,
119+
},
120+
commitNow: true,
121+
})
122+
} catch (error) {
123+
console.error('Network error', error)
124+
} finally {
125+
this.fetchAndInform()
126+
}
106127
}
107128

108129
async clearCompleted() {

0 commit comments

Comments
 (0)