| 15 | onSave: () => void; |
| 16 | onCancel?: () => void; |
| 17 | }> = ({ cta, type, id, index, initialValue, autofocus, onSave, onCancel }) => { |
| 18 | const [formError, setFormError] = useState(null); |
| 19 | const [loading, setLoading] = useState(false); |
| 20 | const { apiCall } = useAuth(); |
| 21 | |
| 22 | const form = useForm({ |
| 23 | defaultValues: { |
| 24 | comment: initialValue || "", |
| 25 | }, |
| 26 | }); |
| 27 | |
| 28 | return ( |
| 29 | <form |
| 30 | onSubmit={form.handleSubmit(async (value) => { |
| 31 | const comment = value.comment; |
| 32 | if (loading || comment.length < 1) return; |
| 33 | setLoading(true); |
| 34 | setFormError(null); |
| 35 | try { |
| 36 | if (index >= 0) { |
| 37 | await apiCall(`/discussion/${type}/${id}/${index}`, { |
| 38 | method: "PUT", |
| 39 | body: JSON.stringify({ comment }), |
| 40 | }); |
| 41 | } else { |
| 42 | await apiCall(`/discussion/${type}/${id}`, { |
| 43 | method: "POST", |
| 44 | body: JSON.stringify({ comment }), |
| 45 | }); |
| 46 | } |
| 47 | form.setValue("comment", ""); |
| 48 | onSave(); |
| 49 | } catch (e) { |
| 50 | setFormError(e.message || "Error saving comment"); |
| 51 | } |
| 52 | |
| 53 | setLoading(false); |
| 54 | })} |
| 55 | > |
| 56 | {loading && <LoadingOverlay />} |
| 57 | <MarkdownInput |
| 58 | value={form.watch("comment")} |
| 59 | setValue={(comment) => form.setValue("comment", comment)} |
| 60 | autofocus={autofocus} |
| 61 | cta={cta} |
| 62 | onCancel={onCancel} |
| 63 | error={formError || ""} |
| 64 | /> |
| 65 | </form> |
| 66 | ); |
| 67 | }; |
| 68 | export default CommentForm; |