fix: prevent duplicate consultations with db unique constraint, frontend init once guard, chat history preserved
This commit is contained in:
@@ -13,6 +13,7 @@ export function ChatPage() {
|
||||
const [text, setText] = useState('');
|
||||
const [sending, setSending] = useState(false);
|
||||
const bottomRef = useRef<HTMLDivElement>(null);
|
||||
const initRef = useRef(false);
|
||||
|
||||
const loadMessages = useCallback((cid: string) => {
|
||||
api.get<ConsultationMessage[]>(`/api/consultations/${cid}/messages`)
|
||||
@@ -20,14 +21,30 @@ export function ChatPage() {
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
// Init once - prevent Strict Mode double-fire
|
||||
useEffect(() => {
|
||||
if (initRef.current) return;
|
||||
initRef.current = true;
|
||||
|
||||
consultationService.getDoctors().then((docs) => {
|
||||
if (docs.length > 0) {
|
||||
const doc = docs[0];
|
||||
setDoctor(doc);
|
||||
consultationService.startConsultation(doc.id, '在线咨询').then((c) => {
|
||||
setConsultation(c);
|
||||
loadMessages(c.id);
|
||||
// Find existing active consultation first
|
||||
api.get<Consultation[]>('/api/consultations').then((res) => {
|
||||
const existing = (res.data as Record<string, unknown>[]).find(
|
||||
(c) => c.doctorId === doc.id && c.status === 'active'
|
||||
);
|
||||
if (existing) {
|
||||
setConsultation(existing as unknown as Consultation);
|
||||
loadMessages((existing as Record<string, string>).id);
|
||||
} else {
|
||||
// Create new only if none exists
|
||||
consultationService.startConsultation(doc.id, '在线咨询').then((c) => {
|
||||
setConsultation(c);
|
||||
loadMessages(c.id);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user