refactor(web): 发送消息

pull/13/head
moonrailgun 4 years ago
parent 99b1a9f67e
commit f5cd580175

@ -16,6 +16,12 @@ export interface ChatMessage {
updatedAt?: string;
}
export interface SendMessagePayload {
groupId?: string;
converseId: string;
content: string;
}
/**
*
* @param converseId ID
@ -34,3 +40,15 @@ export async function fetchConverseMessage(
return data;
}
/**
*
* @param payload
*/
export async function sendMessage(
payload: SendMessagePayload
): Promise<ChatMessage> {
const { data } = await request.post('/api/chat/message/sendMessage', payload);
return data;
}

@ -1,6 +1,12 @@
import { useCallback } from 'react';
import { getCachedConverseInfo } from '../../cache/cache';
import { useAsync } from '../../hooks/useAsync';
import { fetchConverseMessage } from '../../model/message';
import { showErrorToasts } from '../../manager/ui';
import {
fetchConverseMessage,
sendMessage,
SendMessagePayload,
} from '../../model/message';
import { chatActions } from '../slices';
import { useAppDispatch, useAppSelector } from './useAppSelector';
@ -27,5 +33,21 @@ export function useConverseMessage(converseId: string) {
}
}, [converse, converseId]);
return { messages, loading, error };
const handleSendMessage = useCallback(async (payload: SendMessagePayload) => {
// TODO: 增加临时消息, 对网络环境不佳的状态进行优化
try {
const message = await sendMessage(payload);
dispatch(
chatActions.appendConverseMessage({
converseId,
messages: [message],
})
);
} catch (err) {
showErrorToasts(err);
}
}, []);
return { messages, loading, error, handleSendMessage };
}

@ -0,0 +1,14 @@
import { Input } from 'antd';
import React from 'react';
interface ChatInputBoxProps {
onSendMsg: (msg: string) => void;
}
export const ChatInputBox: React.FC<ChatInputBoxProps> = React.memo((props) => {
return (
<div>
<Input onPressEnter={(e) => props.onSendMsg(e.currentTarget.value)} />
</div>
);
});
ChatInputBox.displayName = 'ChatInputBox';

@ -2,6 +2,7 @@ import { Skeleton } from 'antd';
import React from 'react';
import { useConverseMessage } from 'pawchat-shared';
import { AlertErrorView } from '../AlertErrorView';
import { ChatInputBox } from './ChatInputBox';
const ChatBoxPlaceholder: React.FC = React.memo(() => {
return (
@ -24,7 +25,9 @@ ChatBoxPlaceholder.displayName = 'ChatBoxPlaceholder';
export const ChatBox: React.FC<{
converseId: string;
}> = React.memo((props) => {
const { messages, loading, error } = useConverseMessage(props.converseId);
const { messages, loading, error, handleSendMessage } = useConverseMessage(
props.converseId
);
if (loading) {
return <ChatBoxPlaceholder />;
@ -34,6 +37,18 @@ export const ChatBox: React.FC<{
return <AlertErrorView error={error} />;
}
return <div>: {JSON.stringify(messages)}</div>;
return (
<div>
<div>: {JSON.stringify(messages)}</div>
<ChatInputBox
onSendMsg={(msg) =>
handleSendMessage({
converseId: props.converseId,
content: msg,
})
}
/>
</div>
);
});
ChatBox.displayName = 'ChatBox';

Loading…
Cancel
Save