TodoMVC
This is an example of real-time collaborative TodoMVC using CreateReactApp and Yorkie JS SDK.
App.tsx
1import {2 JSONArray,3 JSONObject,4 useDocument,5 useYorkieDoc,6} from '@yorkie-js/react';78import Header from './Header';9import MainSection from './MainSection';10import { Todo } from './model';11import './App.css';1213import 'todomvc-app-css/index.css';1415/**16 * `App` is the root component of the application.17 */18export default function App() {19 const { root, update, loading, error } = useYorkieDoc<{20 todos: JSONArray<Todo>;21 }>(22 import.meta.env.VITE_YORKIE_API_KEY,23 `react-todomvc-${new Date()24 .toISOString()25 .substring(0, 10)26 .replace(/-/g, '')}`,27 {28 initialRoot: {29 todos: [],30 },31 },32 );3334 if (loading) return <div>Loading...</div>;35 if (error) return <div>Error: {error.message}</div>;3637 const actions = {38 addTodo: (text: string) => {39 update((root) => {40 root.todos.push({41 id:42 root.todos.reduce((maxID, todo) => Math.max(todo.id, maxID), -1) +43 1,44 completed: false,45 text,46 });47 });48 },49 deleteTodo: (id: number) => {50 update((root) => {51 let target: (Todo & JSONObject<Todo>) | undefined;52 for (const todo of root.todos) {53 if (todo.id === id) {54 target = todo as Todo & JSONObject<Todo>;55 break;56 }57 }58 if (target) {59 root.todos.deleteByID!(target.getID!());60 }61 });62 },63 editTodo: (id: number, text: string) => {64 update((root) => {65 let target;66 for (const todo of root.todos) {67 if (todo.id === id) {68 target = todo;69 break;70 }71 }72 if (target) {73 target.text = text;74 }75 });76 },77 completeTodo: (id: number) => {78 update((root) => {79 let target;80 for (const todo of root.todos) {81 if (todo.id === id) {82 target = todo;83 break;84 }85 }86 if (target) {87 target.completed = !target.completed;88 }89 });90 },91 clearCompleted: () => {92 update((root) => {93 for (const todo of root.todos) {94 if (todo.completed) {95 const t = todo as Todo & JSONObject<Todo>;96 root.todos.deleteByID!(t.getID!());97 }98 }99 });100 },101 };102103 return (104 <div className="App">105 <Header addTodo={actions.addTodo} />106 <MainSection todos={root.todos} actions={actions} />107 </div>108 );109}
- User 1
- User 2
- User 1
- User 2
Event Log