/
NewNote.js
83 lines (73 loc) · 2.04 KB
/
NewNote.js
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import React, { useRef, useState } from "react";
import { API } from "aws-amplify";
import Form from "react-bootstrap/Form";
import { useHistory } from "react-router-dom";
import LoaderButton from "../components/LoaderButton";
import { onError } from "../libs/errorLib";
import { s3Upload } from "../libs/awsLib";
import config from "../config";
import "./NewNote.css";
export default function NewNote() {
const file = useRef(null);
const history = useHistory();
const [content, setContent] = useState("");
const [isLoading, setIsLoading] = useState(false);
function validateForm() {
return content.length > 0;
}
function handleFileChange(event) {
file.current = event.target.files[0];
}
async function handleSubmit(event) {
event.preventDefault();
if (file.current && file.current.size > config.MAX_ATTACHMENT_SIZE) {
alert(
`Please pick a file smaller than ${
config.MAX_ATTACHMENT_SIZE / 1000000
} MB.`
);
return;
}
setIsLoading(true);
try {
const attachment = file.current ? await s3Upload(file.current) : null;
await createNote({ content, attachment });
history.push("/");
} catch (e) {
onError(e);
setIsLoading(false);
}
}
function createNote(note) {
return API.post("notes", "/notes", {
body: note
});
}
return (
<div className="NewNote">
<Form onSubmit={handleSubmit}>
<Form.Group controlId="content">
<Form.Control
value={content}
as="textarea"
onChange={(e) => setContent(e.target.value)}
/>
</Form.Group>
<Form.Group controlId="file">
<Form.Label>Attachment</Form.Label>
<Form.Control onChange={handleFileChange} type="file" />
</Form.Group>
<LoaderButton
block
type="submit"
size="lg"
variant="primary"
isLoading={isLoading}
disabled={!validateForm()}
>
Create
</LoaderButton>
</Form>
</div>
);
}