|
| 1 | +// -*-RJSX-*- |
| 2 | + |
| 3 | +import React, { useState } from 'react'; |
| 4 | +import LC from 'leancloud-storage'; |
| 5 | +import AppStyles from './App.module.css'; |
| 6 | + |
| 7 | +LC.init('B09iIN0UKf2qQIjqKz5WiRnv-gzGzoHsz', 'Xes23aMR9VUqzpmEvch8YV4A'); |
| 8 | + |
| 9 | +function saveTodo(content) { |
| 10 | + const Todo = LC.Object.extend('Todo'); |
| 11 | + const todo = new Todo(); |
| 12 | + todo.set('content', content); |
| 13 | + todo.set('finished', false); |
| 14 | + return todo.save(); |
| 15 | +} |
| 16 | + |
| 17 | +function loadTodos() { |
| 18 | + const query = new LC.Query('Todo'); |
| 19 | + query.equalTo('finished', false); |
| 20 | + query.limit(20); |
| 21 | + query.descending('createdAt'); |
| 22 | + return query.find(); |
| 23 | +} |
| 24 | + |
| 25 | +function App() { |
| 26 | + const [inputValue, setInputValue] = useState(''); |
| 27 | + const [todos, setTodos] = useState(undefined); |
| 28 | + const [error, setError] = useState(''); |
| 29 | + const addTodo = () => { |
| 30 | + saveTodo(inputValue).then(todo => { |
| 31 | + setInputValue(''); |
| 32 | + setTodos(prev => [todo].concat(prev)); |
| 33 | + }).catch(setError); |
| 34 | + }; |
| 35 | + |
| 36 | + if (todos === undefined) { |
| 37 | + loadTodos().then(setTodos).catch(setError); |
| 38 | + } |
| 39 | + |
| 40 | + const toggle = item => { |
| 41 | + item.set('finished', !item.get('finished')); |
| 42 | + item.save().then(() => setTodos(prev => prev.slice(0))).catch(setError); |
| 43 | + }; |
| 44 | + |
| 45 | + return ( |
| 46 | + <div className={AppStyles.app}> |
| 47 | + <div className={AppStyles.error}>{error.toString()}</div> |
| 48 | + <div className={AppStyles.add}> |
| 49 | + <input placeholder="What to do next?" value={inputValue} |
| 50 | + onChange={e => setInputValue(e.target.value)} |
| 51 | + onKeyUp={e => { if (e.keyCode === 13) addTodo(); } } /> |
| 52 | + <input type="button" value="↩" /> |
| 53 | + </div> |
| 54 | + <ul> |
| 55 | + {todos && todos.map(item => |
| 56 | + <li key={item.getObjectId()} onClick={() => toggle(item)} |
| 57 | + data-finished={item.get('finished')}> |
| 58 | + {item.get('content')} |
| 59 | + </li> )} |
| 60 | + </ul> |
| 61 | + </div> |
| 62 | + ); |
| 63 | +} |
| 64 | + |
| 65 | +export default App; |
0 commit comments