From 68574f0de79ddb9c42149243c50969da66777fbd Mon Sep 17 00:00:00 2001 From: Michael Fatemi Date: Sat, 10 Apr 2021 17:50:12 -0400 Subject: [PATCH] Add nice UI for posting comments --- src/components/Pool.tsx | 60 ++++++++++++++++++++++++++++++++++------- 1 file changed, 50 insertions(+), 10 deletions(-) diff --git a/src/components/Pool.tsx b/src/components/Pool.tsx index bfcfc28..00ba16a 100644 --- a/src/components/Pool.tsx +++ b/src/components/Pool.tsx @@ -1,10 +1,12 @@ -import { useState, useEffect, FormEventHandler, useCallback } from 'react'; +import { useState, useEffect, useCallback, useRef } from 'react'; import { useParams } from 'react-router'; import Button from '@material-ui/core/Button'; import Card from '@material-ui/core/Card'; import Textarea from '@material-ui/core/TextareaAutosize'; import Typography from '@material-ui/core/Typography'; import Comment from './Comment'; +import getSessionId from '../lib/getSessionId'; +import { makeAPIPostCall } from '../api/utils'; export default function Pool({ registered = false }: { registered?: boolean }) { const id = useParams<{ id: string }>().id; @@ -32,15 +34,41 @@ export default function Pool({ registered = false }: { registered?: boolean }) { author_id: 'michael', type: 'offer', }); - const onComment = useCallback>((e) => { - e.preventDefault(); - fetch(`${process.env.REACT_APP_API_ENDPOINT}/pool/comments`) - .then((response) => response.json()) - .then((data) => { - console.log(data); - }); - }, []); + const commentTextareaRef = useRef(null); + const [commentStatus, setCommentStatus] = useState< + null | 'pending' | 'errored' + >(null); + + const onComment = useCallback>( + (e) => { + e.preventDefault(); + + if (!commentTextareaRef.current) { + // Wait for ref to be ready + return; + } + + if (commentTextareaRef.current.value.length === 0) { + // Noop, no comment to send + return; + } + + setCommentStatus('pending'); + + makeAPIPostCall('/comment', { + body: commentTextareaRef.current!.value, + }) + .then(() => { + setCommentStatus(null); + commentTextareaRef.current!.value = ''; + }) + .catch(() => { + setCommentStatus('errored'); + }); + }, + [] + ); useEffect(() => { fetch(`${process.env.REACT_APP_API_ENDPOINT}/pool/${id}`) @@ -77,10 +105,22 @@ export default function Pool({ registered = false }: { registered?: boolean }) {