From 31b97eaa595f960ca238f12137f811cb5264b54b Mon Sep 17 00:00:00 2001 From: Guillaume Dorce Date: Sun, 25 Sep 2022 17:41:19 +0200 Subject: [PATCH] scroll to bottom when new message and prevent sending empty message --- client/src/components/Message.tsx | 5 ++--- client/src/components/MessageWrapper.tsx | 4 +--- client/src/components/NewMessage.tsx | 13 +++++++++---- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/client/src/components/Message.tsx b/client/src/components/Message.tsx index 2ea8a98..78737a4 100644 --- a/client/src/components/Message.tsx +++ b/client/src/components/Message.tsx @@ -29,11 +29,10 @@ const Likes = ({ likes }: {likes: number}) => { ); }; -const Message = ({ text = '', user, date, image = '' }: any) => { - const id = '1'; // replace with real id in the future +const Message = ({ text = '', user, date, image = '', id }: any) => { return ( <> -
+
{user && }
diff --git a/client/src/components/MessageWrapper.tsx b/client/src/components/MessageWrapper.tsx index a3b87c7..756098a 100644 --- a/client/src/components/MessageWrapper.tsx +++ b/client/src/components/MessageWrapper.tsx @@ -18,8 +18,6 @@ const getMessages = async () => { const MessageWrapper = () => { const messages = useQuery(["messages"], getMessages, { onSuccess: (data) => { - console.log(data); - return data; }, onError: (error) => { @@ -36,7 +34,7 @@ const MessageWrapper = () => { return (
{messages.isLoading ? '' : messages.data?.map((message: any) => ( - + ))}
); diff --git a/client/src/components/NewMessage.tsx b/client/src/components/NewMessage.tsx index d32fdf3..9bb895b 100644 --- a/client/src/components/NewMessage.tsx +++ b/client/src/components/NewMessage.tsx @@ -7,9 +7,8 @@ const sendMessage = async (data: FormData) => { const token = new Cookies().get('token'); let contentType = 'application/json'; let body: FormData | string | undefined = undefined; - console.log(data.get('image')); - if (data.get('image')?.name !== "") { + if (data.get('image')) { contentType = 'multipart/form-data'; body = data; } else { @@ -32,9 +31,12 @@ const NewMessage = () => { const queryClient = useQueryClient(); const { mutate: send } = useMutation(sendMessage, { - onSuccess: (data) => { - console.log(data); + onSuccess: () => { queryClient.invalidateQueries(['messages']); + const messageWrapper = document.querySelector('.messages-wrapper'); + messageWrapper?.addEventListener('DOMNodeInserted', () => { + messageWrapper?.scrollTo(0, messageWrapper.scrollHeight); + }); }, onError: (error) => { console.error(error); @@ -43,6 +45,9 @@ const NewMessage = () => { const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); + if (message.trim().length === 0 && image.trim().length === 0) { + return; + } const data = new FormData(e.target as HTMLFormElement); send(data); setMessage('');