Sure! Below is the fully updated ChatApp React component that accommodates both scenarios for creating a new session:
- Initial Message on a Null Session: When the user sends a message without an existing session, a new session is created, and the initial message is included in that session.
- Using the "New Session" Button: When the user clicks the "New Session" button, a new session is created without requiring any initial message.
Key Changes:
createNewSession Function: Modified to return a promise, enabling handleSend to await its completion when creating a new session with an initial message.
handleSend Function: Adjusted to handle both scenarios by checking if there's an existing session. If not, it creates a new session with the initial message and then proceeds to interact with the chatbot.
- String Interpolation: Fixed template literals to use backticks appropriately.
- Dependencies in
useEffect: Added currentUser.uid to the dependencies array to ensure sessions are loaded correctly when the user changes.
Please ensure that the currentUser object is properly defined and accessible within the component. If you're using Firebase Authentication, you might obtain it from there.
Here's the complete updated script:
import React, { useState, useEffect } from 'react';
import { getDatabase, ref, set, push, update, onValue } from 'firebase/database';
import { getAuth, onAuthStateChanged } from 'firebase/auth';
const ChatApp = () => {
const [input, setInput] = useState('');
const [messages, setMessages] = useState([]);
const [sessions, setSessions] = useState([]);
const [currentSession, setCurrentSession] = useState(null);
const [isSending, setIsSending] = useState(false);
const db = getDatabase();
const auth = getAuth();
const [currentUser, setCurrentUser] = useState(null);
// Monitor authentication state
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (user) => {
if (user) {
setCurrentUser(user);
} else {
setCurrentUser(null);
}
});
return () => unsubscribe();
}, [auth]);
// Load sessions from Firebase when currentUser changes
useEffect(() => {
if (!currentUser) return;
const sessionsRef = ref(db, `chats/${currentUser.uid}/sessions`);
const unsubscribe = onValue(sessionsRef, (snapshot) => {
const sessionData = snapshot.val();
if (sessionData) {
setSessions(Object.entries(sessionData));
} else {
setSessions([]);
}
});
return () => unsubscribe();
}, [db, currentUser]);
// Load messages when currentSession changes
useEffect(() => {
if (!currentSession || !currentUser) {
setMessages([]);
return;
}
const messagesRef = ref(db, `chats/${currentUser.uid}/sessions/${currentSession}/messages`);
const unsubscribe = onValue(messagesRef, (snapshot) => {
const messagesData = snapshot.val();
if (messagesData) {
setMessages(messagesData);
} else {
setMessages([]); // Clear messages if no data
}
});
return () => unsubscribe();
}, [db, currentSession, currentUser]);
const handleSend = async () => {
if (input.trim() === '' || isSending || !currentUser) return;
const userMessage = { sender: 'user', text: input.trim() };
setIsSending(true);
try {
// If there's no current session, create a new one with the initial message
if (!currentSession) {
await createNewSession(userMessage);
} else {
const updatedMessages = [...messages, userMessage];
setMessages(updatedMessages); // Update state with the new message
// Save messages to Firebase
const sessionRef = ref(db, `chats/${currentUser.uid}/sessions/${currentSession}/messages`);
await set(sessionRef, updatedMessages); // Save updated messages
}
// Chatbot interaction
const FUNCTION_URL = 'https://us-central1-mind-gardener.cloudfunctions.net/chatWithHuggingFace';
const response = await fetch(FUNCTION_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ conversationHistory: currentSession ? [...messages, userMessage] : [userMessage] }),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || 'Server error');
}
const result = await response.json();
const botReply = result.reply || 'No response from bot';
// Save bot reply and update messages
const botMessage = { sender: 'bot', text: botReply };
const updatedMessagesWithBotReply = currentSession
? [...messages, userMessage, botMessage]
: [userMessage, botMessage];
setMessages(updatedMessagesWithBotReply);
// Save both user and bot messages to Firebase
const sessionRef = ref(db, `chats/${currentUser.uid}/sessions/${currentSession}/messages`);
await set(sessionRef, updatedMessagesWithBotReply);
} catch (error) {
setMessages((prev) => [
...prev,
{ sender: 'bot', text: `Sorry, there was an error: ${error.message}` },
]);
} finally {
setIsSending(false);
setInput('');
}
};
const createNewSession = async (userMessage = null) => {
if (!currentUser) return;
const newSessionLabel = `Session ${sessions.length + 1}`; // Labeling new session sequentially
const sessionsRef = ref(db, `chats/${currentUser.uid}/sessions`);
const newSessionRef = push(sessionsRef);
const sessionId = newSessionRef.key;
// Initialize messages as an empty array or include the user message
const initialMessages = userMessage ? [userMessage] : [];
// Create the session in the database
await update(newSessionRef, { name: newSessionLabel, messages: initialMessages });
// Update local sessions state
setSessions((prev) => [
...prev,
[sessionId, { name: newSessionLabel, messages: initialMessages }],
]);
// Load the new session
setCurrentSession(sessionId);
setMessages(initialMessages);
};
const handleNewSession = () => {
// Create a new session without an initial message
createNewSession();
};
const handleSelectSession = (sessionId) => {
setCurrentSession(sessionId);
};
return (
<div style={styles.container}>
<div style={styles.sidebar}>
<h2>Sessions</h2>
<button onClick={handleNewSession} style={styles.newSessionButton}>New Session</button>
<ul style={styles.sessionList}>
{sessions.map(([id, session]) => (
<li
key={id}
onClick={() => handleSelectSession(id)}
style={{
...styles.sessionItem,
backgroundColor: id === currentSession ? '#e0e0e0' : 'transparent',
cursor: 'pointer',
}}
>
{session.name}
</li>
))}
</ul>
</div>
<div style={styles.chatContainer}>
<div style={styles.chatbox}>
{messages.map((msg, index) => (
<div
key={index}
style={{
...styles.message,
alignSelf: msg.sender === 'bot' ? 'flex-start' : 'flex-end',
backgroundColor: msg.sender === 'bot' ? '#f1f0f0' : '#0084ff',
color: msg.sender === 'bot' ? '#000' : '#fff',
}}
>
{msg.text}
</div>
))}
</div>
<div style={styles.inputContainer}>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Type your message..."
style={styles.input}
onKeyPress={(e) => {
if (e.key === 'Enter') {
handleSend();
}
}}
disabled={isSending}
/>
<button onClick={handleSend} style={styles.sendButton} disabled={isSending}>
{isSending ? 'Sending...' : 'Send'}
</button>
</div>
</div>
</div>
);
};
// Basic inline styles for better UI presentation
const styles = {
container: {
display: 'flex',
height: '100vh',
fontFamily: 'Arial, sans-serif',
},
sidebar: {
width: '250px',
borderRight: '1px solid #ccc',
padding: '20px',
boxSizing: 'border-box',
},
newSessionButton: {
width: '100%',
padding: '10px',
marginBottom: '20px',
backgroundColor: '#28a745',
color: '#fff',
border: 'none',
cursor: 'pointer',
},
sessionList: {
listStyleType: 'none',
padding: 0,
},
sessionItem: {
padding: '10px',
borderBottom: '1px solid #ddd',
},
chatContainer: {
flex: 1,
display: 'flex',
flexDirection: 'column',
padding: '20px',
boxSizing: 'border-box',
},
chatbox: {
flex: 1,
overflowY: 'auto',
display: 'flex',
flexDirection: 'column',
gap: '10px',
marginBottom: '20px',
},
message: {
maxWidth: '60%',
padding: '10px',
borderRadius: '10px',
},
inputContainer: {
display: 'flex',
},
input: {
flex: 1,
padding: '10px',
fontSize: '16px',
border: '1px solid #ccc',
borderRadius: '4px',
},
sendButton: {
padding: '10px 20px',
marginLeft: '10px',
backgroundColor: '#007bff',
color: '#fff',
border: 'none',
borderRadius: '4px',
cursor: 'pointer',
},
};
export default ChatApp;
Explanation of the Changes:
-
Authentication Handling:
- Added Firebase Authentication listener using
onAuthStateChanged to manage currentUser. This ensures that the component reacts to authentication state changes.
- The
currentUser state is used to reference the user's UID for Firebase database paths.
-
Session Loading:
- The
useEffect that loads sessions now depends on both db and currentUser. It fetches sessions specific to the authenticated user.
- Another
useEffect is added to load messages whenever the currentSession changes.
-
handleSend Function:
- Now
handleSend is an asynchronous function that handles both creating a new session (if none exists) and sending messages within an existing session.
- When there's no
currentSession, it awaits the creation of a new session with the initial message and then proceeds to interact with the chatbot.
-
createNewSession Function:
- Modified to be asynchronous and return a promise, ensuring that session creation is complete before proceeding.
- After creating a new session, it updates the local
sessions state and sets the new session as the currentSession.
-
UI Enhancements:
- Added a sidebar to list all sessions with a "New Session" button.
- Implemented basic styling for better user experience.
- Messages are displayed with differentiation between user and bot messages for clarity.
-
Error Handling & UX:
- Disabled the input and send button while sending a message to prevent duplicate sends.
- Added the ability to press the "Enter" key to send messages.
- Displayed a loading state ("Sending...") on the send button when a message is being sent.
-
Template Literals:
- Corrected all Firebase database paths to use proper template literals with backticks (
`).
Notes:
-
Firebase Initialization: Ensure that Firebase is properly initialized in your project and that the Firebase SDKs for Authentication and Realtime Database are correctly set up.
-
Authentication: This implementation assumes that users are authenticated. If you haven't set up Firebase Authentication, you'll need to do so or modify the code to handle unauthenticated users appropriately.
-
Chatbot Function: Ensure that the chatWithHuggingFace Cloud Function is deployed and accessible at the specified FUNCTION_URL.
-
Styling: The inline styles provided are basic. For a production application, consider using CSS modules or styled-components for better styling practices.
-
Session Selection: Added functionality to select and load different sessions from the sidebar.
This updated script should fulfill the requirements by handling both scenarios for creating new chat sessions, providing a more robust and user-friendly chat application.