Я создаю простое приложение для чата в реагировании с помощью пользовательского крючка, который получает чаты из службы, как только клиент WebSocke подключен. Он показывает данные только после того, как я запускаю другое обновление состояния, нажав кнопку.import { useEffect, useState } from "react";
import ChatService from "../services/chat-service";
import { Client } from "@stomp/stompjs";
import Conversation from "../entities/chat/Conversation";
import Account from "../entities/user/Account";
import Message from "../entities/chat/Message";
export default function useChat(){
const [loading,setLoading] = useState(true)
const [client,setClient] = useState(null)
const [chat,setChat] = useState(null);
useEffect(()=>{
const initSocket = async ()=>{
const client = await ChatService.initialSocketConnnection((message)=>{
console.log(message);
})
setClient(client)
}
initSocket()
return ()=>{
client?.deactivate();
setClient(null);
}
},[])
useEffect(()=>{
if (!client) return;
const initChat = async ()=>{
const chats = await ChatService.getChat()
console.log('Fetched chats:', chats);
setChat(chats);
setLoading(false)
}
initChat()
return ()=>{
setChat(null);
setLoading(true)
}
}, [client])
const sendMessage = (destination:Account,message:Message) => {
if(!client) return
ChatService.sendMessage(destination.username,message,client);
}
return {sendMessage,loading,chat}
}
< /code>
А вот компонент чата < /p>
import { useState } from "react"
import Card from "../components/ui/Card"
import useChat from "../hooks/useChat"
export default function Chat(){
const {sendMessage,loading,chat} = useChat()
const [test,setTest]= useState(0);
if(loading) return Loading
return
Messages
{loading?"loading":"not Loading"}
{Array.isArray(chat) && chat.length > 0 ? (
chat.map((element, index) => (
{JSON.stringify(element)}
))
) : (
No chats yet
)}
{test}
{setTest(chat?.length)}}>
Increment
}
Подробнее здесь: https://stackoverflow.com/questions/797 ... -on-change