我正在React Native应用中使用Rest Apis执行聊天模块,我想使其实时化,如何将其与Socket.io一起使用。这是我在其中获取消息并与他人发送消息的代码所有这些实时与socket.io。请帮助
componentDidMount() {
this.fetchMessages();
}
fetchMessages = async () => {
const Pid = await AsyncStorage.getItem("projectUid");
const { params } = this.props.navigation.state;
const response = await fetch(
CONSTANT.BaseUrl + "chat/list_user_messages?current_id=" + Pid + "&reciver_id=" + params.receiver_id + "&msg_id=" + params.message_id
);
const json = await response.json();
if (Array.isArray(json) && json[0] && json[0].type && json[0].type === 'error') {
this.setState({ fetchMessageDetail: [] ,isLoading:false}); // empty data set
} else {
this.setState({ fetchMessageSenderDetail: json.chat_sidebar , isLoading:false });
this.setState({ fetchMessageDetail: json.chat_nodes , isLoading:false });
}
};
SendMessage = async () => {
const { message } = this.state;
const { params } = this.props.navigation.state;
const Uid = await AsyncStorage.getItem("projectUid");
if (message == "") {
//alert("Please enter Email address");
this.setState({ email: "Please add message" });
} else {
axios
.post(
CONSTANT.BaseUrl + "chat/sendUserMessage",
{
sender_id: Uid,
receiver_id: params.receiver_id,
message:message,
}
)
.then(async response => {
this.setState({
message:''
})
this.fetchMessages();
})
.catch(error => {
console.log(error);
});
}
Keyboard.dismiss();
};