-
-
Notifications
You must be signed in to change notification settings - Fork 92
/
NewTodo.tsx
50 lines (46 loc) · 1.27 KB
/
NewTodo.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
import { useController } from 'rest-hooks';
import { useCallback, useRef, useState } from 'react';
import { styled } from '@linaria/react';
import TodoResource from 'resources/TodoResource';
export default function NewTodo({ lastId }: { lastId: number }) {
const { fetch } = useController();
const [title, setTitle] = useState('');
const handleChange = useCallback((e) => {
setTitle(e.currentTarget.value);
}, []);
// this allows handlePress to never change referential equality
const payload = useRef({ id: lastId + 1, title: title });
payload.current = { id: lastId + 1, title: title };
const handlePress = useCallback(
async (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
fetch(TodoResource.create(), {}, payload.current);
setTitle('');
}
},
[fetch],
);
return (
<TodoBox>
<input type="checkbox" name="new" checked={false} disabled />{' '}
<TitleInput
type="text"
value={title}
onChange={handleChange}
onKeyPress={handlePress}
/>
</TodoBox>
);
}
const TodoBox = styled.div`
text-align: left;
display: flex;
`;
const TitleInput = styled.input`
flex: 1 1 auto;
width: 100%;
background: #e1e1e1;
&:focus {
background: eeeeee;
}
`;