-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTweetForm.tsx
43 lines (39 loc) · 1.2 KB
/
TweetForm.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
"use client";
import { useRef, useState } from "react";
import { addTweet } from "./actions";
import { experimental_useFormStatus as useFormStatus } from "react-dom";
export default function TweetForm() {
const [error, setError] = useState<string | null>(null);
const form = useRef<HTMLFormElement>(null);
const { pending } = useFormStatus();
return (
<>
<form
action={async (formData) => {
setError(null);
const tweet = formData.get("tweet");
if (typeof tweet !== "string" || tweet.length === 0) {
setError("Tweet cannot be empty");
return;
}
if (tweet.length > 140) {
setError("Tweet cannot be longer than 140 characters");
return;
}
const result = await addTweet(tweet);
if (result.success === false) {
setError(result.error);
return;
}
form.current?.reset();
}}
ref={form}
>
<textarea name="tweet"></textarea>
<button disabled={pending}>Tweet</button>
{pending && <p>Submitting...</p>}
{error && <p style={{ color: "red" }}>{error}</p>}
</form>
</>
);
}