scroll to bottom when new message and prevent sending empty message

This commit is contained in:
Guillaume Dorce 2022-09-25 17:41:19 +02:00
parent ac3a0fb3a8
commit 31b97eaa59
3 changed files with 12 additions and 10 deletions

View File

@ -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 (
<>
<div className="flex bg-grey-dark rounded-xl w-full max-w-3xl p-5 gap-5 shadow-md shadow-grey-dark">
<div className="flex bg-grey-dark rounded-xl w-full max-w-3xl p-5 gap-5 shadow-md shadow-grey-dark" id={"messageId" + id}>
{user && <Avatar user={user} />}
<div className="flex flex-col gap-2 relative flex-grow">
<div className="flex justify-between">

View File

@ -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 (
<main className="messages-wrapper flex flex-col p-4 gap-4 overflow-scroll w-full max-w-3xl">
{messages.isLoading ? '' : messages.data?.map((message: any) => (
<Message user={message.author} text={message.content} image={message.image} date={message.createdAt}/>
<Message user={message.author} text={message.content} image={message.image} date={message.createdAt} id={message.id}/>
))}
</main>
);

View File

@ -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('');