removed temp message

This commit is contained in:
slawk0
2024-12-07 19:29:22 +01:00
parent e2e34f9776
commit 15a3215a7e
5 changed files with 31 additions and 63 deletions

View File

@@ -2,13 +2,10 @@ import { useRef, useCallback, useEffect, useState } from 'react';
import { useForm, SubmitHandler } from 'react-hook-form';
import type { KeyboardEventHandler } from 'react';
import { socket } from '../../socket/socket.tsx';
import { customAlphabet } from 'nanoid';
import { useOutletContext } from 'react-router-dom';
import { ChatMessages, ContactsProps } from '../../pages/Chat.tsx';
import { axiosClient } from '../../App.tsx';
import { File, Paperclip, X } from 'lucide-react';
const nanoid = customAlphabet('1234567890', 5);
import LoadingWheel from '@/components/chat/LoadingWheel.tsx';
type Input = {
message: string;
@@ -26,10 +23,11 @@ type FileWithPreview = {
preview: string | null;
};
const MessageForm = ({ contact, setMessages }: MessageFormProps) => {
const { username }: { username: string } = useOutletContext();
const MessageForm = ({ contact }: MessageFormProps) => {
const [files, setFiles] = useState<FileWithPreview[]>([]);
const [isUploading, setIsUploading] = useState(false);
const [isSending, setIsSending] = useState<boolean>(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const fileInputRef = useRef<HTMLInputElement | null>(null);
@@ -119,9 +117,11 @@ const MessageForm = ({ contact, setMessages }: MessageFormProps) => {
};
// Sending message
const submitMessage: SubmitHandler<Input> = async (data) => {
if (!data.message && files.length === 0) return;
// Inside the MessageForm component
const submitMessage: SubmitHandler<Input> = async (data) => {
if ((!data.message && files.length === 0) || isSending) return;
setIsSending(true);
if (!socket) {
console.error('Socket not initialized');
return;
@@ -138,56 +138,25 @@ const MessageForm = ({ contact, setMessages }: MessageFormProps) => {
}
}
const tempId: string = nanoid();
const tempMessage: ChatMessages = {
sender: username,
message: data.message.trim(),
recipient: contact.conversation_id,
message_id: 0,
pending: true,
tempId: tempId,
attachment_urls: attachmentUrls,
sender_id: 0,
conversation_id: 0,
};
setMessages((prevMessages) => [...prevMessages, tempMessage]);
// Emit message to server
socket.emit(
'chat message',
{
message: data.message.trim(),
recipient: contact.conversation_id,
tempId: tempId,
attachment_urls: attachmentUrls,
recipient_id: contact.user_id,
},
(response: {
status: string;
message_id: number;
tempId: number;
message: string;
}) => {
(response: { status: string; message: string }) => {
if (response.status === 'ok') {
setMessages((prevMessages) =>
prevMessages.map((msg) =>
msg.tempId === tempId
? {
...msg,
pending: false,
message_id: response.message_id,
sender_id: msg.sender_id,
}
: msg,
),
);
setIsSending(false);
reset({ message: '' });
handleClearFiles();
} else {
setIsSending(false);
setErrorMessage(response.message);
}
console.log(
`status: ${response.status}, tempId: ${response.tempId}, message: ${response.message}`,
);
console.log('Response: ', response);
},
);
};
@@ -309,6 +278,7 @@ const MessageForm = ({ contact, setMessages }: MessageFormProps) => {
</span>
</div>
</div>
{errorMessage ? <p className="text-red-200">{errorMessage}</p> : null}
<div className="flex gap-2">
<label
htmlFor="attachments"
@@ -333,9 +303,9 @@ const MessageForm = ({ contact, setMessages }: MessageFormProps) => {
<button
className="text-black bg-green-500 hover:bg-green-400 font-bold py-2 px-4 rounded w-24 shrink-0 disabled:opacity-50 disabled:cursor-not-allowed"
type="submit"
disabled={isOverLimit || isUploading}
disabled={isOverLimit || isSending || isUploading}
>
Send
{isSending ? <LoadingWheel /> : <p>send</p>}
</button>
</div>
</div>

View File

@@ -131,10 +131,7 @@ function MessagesArea({
false,
);
}
if (
msg.conversation_id == currentContact?.conversation_id &&
msg.sender !== username
) {
if (msg.conversation_id == currentContact?.conversation_id) {
messageHandler(msg);
}
});
@@ -173,11 +170,13 @@ function MessagesArea({
className={`whitespace-pre-wrap ml-2 rounded p-1 group ${
msg.pending ? 'text-gray-400' : 'hover:bg-gray-900'
}`}
key={msg.message_id || msg.tempId}
key={msg.message_id}
>
<div className="flex items-center justify-between">
<div>
{msg.sender}: {msg.message}
<span title={new Date(msg.sent_at).toLocaleTimeString()}>
{msg.sender}: {msg.message}
</span>
{msg.attachment_urls && (
<div className="mt-2 flex flex-col gap-2">
{msg.attachment_urls.length > 0

View File

@@ -16,11 +16,11 @@ export type ChatMessages = {
message: string;
recipient: number; // conversation_id
message_id: number;
tempId: string;
pending: boolean;
attachment_urls: string[] | null;
sender_id: number;
conversation_id: number;
sent_at: Date;
};
export type ContactsProps = {
@@ -147,7 +147,12 @@ function Chat() {
setMessages((prevMessages) => {
// Check if the message already exists in the state
if (!prevMessages.some((m) => m.message_id === msg.message_id)) {
return [...prevMessages, msg];
// Convert sent_at to Date object before adding to state
const messageWithDate = {
...msg,
sent_at: new Date(msg.sent_at),
};
return [...prevMessages, messageWithDate];
}
return prevMessages;
});

View File

@@ -30,7 +30,6 @@ function sendMessage(message: string, recipient: string, tempId: string) {
{
message: message,
recipient: recipient,
tempId: tempId,
},
(response: { status: string; tempId: string }) => {
console.log(response.status, response.tempId);
@@ -40,7 +39,6 @@ function sendMessage(message: string, recipient: string, tempId: string) {
console.log('sent message: ', {
message: message,
recipient: recipient,
tempId: tempId,
});
}

View File

@@ -81,7 +81,6 @@ function initializeSocket(io) {
if (!message && !attachment_urls) {
callback({
status: "error",
tempId: msg.tempId,
message: "No message or attachment provided",
});
return;
@@ -89,7 +88,6 @@ function initializeSocket(io) {
if (!recipient) {
callback({
status: "error",
tempId: msg.tempId,
message: "No recipient provided",
});
return;
@@ -104,7 +102,6 @@ function initializeSocket(io) {
);
if (!insertedMessage) {
callback({
tempId: msg.tempId,
status: "error",
message: "Failed to insert message",
});
@@ -136,14 +133,13 @@ function initializeSocket(io) {
});
callback({
message_id,
status: "ok",
tempId: msg.tempId,
message: "Received message",
});
} catch (e) {
console.error("(socket) Failed to insert message ", e);
callback({
tempId: msg.tempId,
status: "error",
message: "Internal server error",
});