From f7921fb0574ea2ff4eb434185e89df43a1d4ef47 Mon Sep 17 00:00:00 2001 From: bhuwan joshi Date: Mon, 11 Mar 2024 09:18:02 +0530 Subject: [PATCH] Basic chat session created --- network/chat_session.js | 5 +++++ screens/ChatSessionScreen.js | 21 +++++++++++---------- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/network/chat_session.js b/network/chat_session.js index 7fed132a..e19cd2b3 100644 --- a/network/chat_session.js +++ b/network/chat_session.js @@ -11,3 +11,8 @@ export const getChatSession = async (chatSessionId, lastMessageId) => { `chat_sessions/${chatSessionId}/new_messages?last_message_id=${lastMessageId}&format=json` ); }; + +export const followUpChatSession = async (id, chatSession) => { + const axiosClient = await getAxiosClient(); + return axiosClient.patch(`chat_sessions/${id}.json`, chatSession); +}; diff --git a/screens/ChatSessionScreen.js b/screens/ChatSessionScreen.js index c13b5d81..d0346596 100644 --- a/screens/ChatSessionScreen.js +++ b/screens/ChatSessionScreen.js @@ -3,7 +3,7 @@ import React, { useState, useEffect } from 'react'; import { material } from 'react-native-typography'; import { logEvent } from '../libs/Helpers'; import { useTranslation } from 'react-i18next'; -import { createChatSession, getChatSession } from '../network/chat_session'; +import { createChatSession, followUpChatSession, getChatSession } from '../network/chat_session'; import { retrieveUserSession } from '../libs/EncryptedStoreage'; import ChatCard from '../components/ChatCard'; @@ -35,20 +35,21 @@ const ChatSessionScreen = ({ navigation }) => { } }; try { - const chatSession = await createChatSession(message); - setMessages([...messages, ...chatSession.data.messages]); + let chatSession; + if (messages.length === 0) { + chatSession = await createChatSession(message); + } else { + chatSession = await followUpChatSession(messages[0].chat_session_id, message); + } + const latestMessage = chatSession.data.messages[chatSession.data.messages.length - 1]; + setMessages([...messages, latestMessage]); const interval = setInterval(async () => { - const messageResponse = await getChatSession( - chatSession.data.id, - chatSession.data.messages[0].id - ); + const messageResponse = await getChatSession(chatSession.data.id, latestMessage.id); if (messageResponse.data.length > 0) { - console.log('messageResponse', messageResponse); clearInterval(interval); setMessages((messages) => [...messages, ...messageResponse.data]); } - }, 1000); - // setMessages([...messages, newMessage]); + }, 2000); setInputText(''); } catch (error) { console.error('Error sending message', error);