-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Todos.tsx
68 lines (65 loc) · 1.8 KB
/
Todos.tsx
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
import React from "react";
import { useY } from "react-yjs";
import * as Y from "yjs";
export const Todos: React.FC = () => {
const [yTodos] = React.useState(() => {
// initialize a Y.Doc and get the todos array
// when the component mounts
const yDoc = new Y.Doc();
return yDoc.getArray<Y.Map<string | boolean>>("todos");
});
const todos = useY(yTodos);
const [newTodo, setNewTodo] = React.useState("");
return (
<>
<form
onSubmit={(event) => {
event.preventDefault();
const todo = new Y.Map<string | boolean>();
todo.set("checked", false);
todo.set("text", newTodo);
yTodos.push([todo]);
setNewTodo("");
}}
>
<label>
<input
type="text"
value={newTodo}
onChange={(event) => {
setNewTodo(event.currentTarget.value);
}}
/>
</label>
<button>Add</button>
</form>
<ul>
{todos.map((todo, index) => {
return (
<li key={index}>
<label>
<input
type="checkbox"
checked={todo.checked as boolean}
onChange={(event) => {
yTodos
.get(index)
.set("checked", event.currentTarget.checked);
}}
/>
<input
type="text"
value={todo.text as string}
onChange={(event) => {
yTodos.get(index).set("text", event.currentTarget.value);
}}
/>
</label>
</li>
);
})}
</ul>
<div>Result: {JSON.stringify(todos, null, 2)}</div>
</>
);
};