The following code is the App.js for a React app of a… · The Chat Archive
Explore / Programming The following code is the App.js for a React app of a chatbot interface. Please fix all… Save Share Download ▾ ReportThe following code is the App.js for a React app of a chatbot interface. Please fix all errors you find:
App.js:
import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import Sidebar from './components/Sidebar';
import Header from './components/Header';
import ChatWindow from './components/ChatWindow';
import CodeSidebar from './components/CodeSidebar';
import { FaSearch } from 'react-icons/fa';
import {
sendMessage as sendMessageAction,
startNewChat,
setCodeSnippet,
} from './redux/chatSlice';
function App() {
const dispatch = useDispatch();
const {
input, // Managed locally
chats,
activeChat,
codeSnippet,
commonQueries,
status,
error,
} = useSelector((state) => state.chat);
const [localInput, setLocalInput] = React.useState('');
// Handle sending a message
const sendMessage = () => {
if (localInput.trim() === '') return;
// Dispatch sendMessage async thunk
dispatch(sendMessageAction({ text: localInput, activeChat }));
setLocalInput('');
};
// Start a new chat
const handleStartNewChat = () => {
dispatch(startNewChat());
};
// Handle code click
const handleCodeClick = (code) => {
dispatch(setCodeSnippet(code));
};
// Optionally, handle error state
useEffect(() => {
if (status === 'failed') {
console.error(error);
}
}, [status, error]);
return (
Show full message · 460 lines Assistant2024-09-21 01:47 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Conversation date Sep 21, 2024
Added to archive Nov 16, 2026
ID 01m7h41vbjwz7fpebxwh4st8jzSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: a3c96782059a6ebffb8e1186e1390ad6
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
{/ Main Content /}
<div className="flex-1 flex flex-col">
{/ Header /}
<Header />
{/ Search Box and Common Queries (Visible when no active chat) /}
{activeChat === null && (
<div className="p-4 bg-gray-100">
{/ Search Box /}
<div className="flex mb-4">
<input
type="text"
className="flex-grow border rounded-l px-4 py-2 focus:outline-none"
placeholder="Enter your query..."
value={localInput}
onChange={(e) => setLocalInput(e.target.value)}
onKeyPress={(e) => {
if (e.key === 'Enter') sendMessage();
}}
/>
<button
className="bg-blue-500 text-white px-4 py-2 rounded-r hover:bg-blue-600"
onClick={sendMessage}
>
<FaSearch />
</button>
</div>
{/ Common Queries /}
<div>
<h3 className="text-lg font-semibold mb-2">Common Queries:</h3>
<div className="flex flex-wrap gap-2">
{commonQueries.map((query, index) => (
<button
key={index}
className="bg-gray-200 text-gray-800 px-3 py-1 rounded hover:bg-gray-300"
onClick={() => setLocalInput(query)}
>
{query}
</button>
))}
</div>
</div>
</div>
)}
{/ Chat Window (Visible when a chat is active) /}
{activeChat !== null && (
<ChatWindow
messages={chats[activeChat]}
onSend={sendMessage}
input={localInput}
setInput={setLocalInput}
onCodeClick={handleCodeClick}
/>
)}
</div>
{/ Code Sidebar */}
{codeSnippet && (
<CodeSidebar onClose={() => dispatch(setCodeSnippet(null))} code={codeSnippet} />
)}
</div>
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import store from './redux/store'; // Import the store
import { Provider } from 'react-redux'; // Import Provider
ReactDOM.render(
<React.StrictMode>
</React.StrictMode>,
document.getElementById('root')
);
ChatWindow.js:
import React, { useRef, useEffect } from "react";
import { FaCopy } from "react-icons/fa";
function ChatWindow({ messages, onSend, input, setInput, onCodeClick }) {
const messagesEndRef = useRef(null);
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
};
useEffect(scrollToBottom, [messages]);
return (
{messages.map((msg, index) => (
<div
key={index}
className={mb-4 flex ${ msg.sender === "user" ? "justify-end" : "justify-start" }}
>
<div
className={px-4 py-2 rounded-lg max-w-xs ${ msg.sender === "user" ? "bg-blue-500 text-white" : "bg-white text-gray-800 shadow" }}
onClick={() => {
if (msg.isCode && onCodeClick) onCodeClick(msg.code);
}}
>
{msg.isCode ? (
{msg.code.length > 100
? ${msg.code.substring(0, 100)}...
: msg.code}
{msg.code.length > 100 && (
Click to expand
)}
) : (
msg.text
)}
))}
<input
type="text"
className="flex-grow border rounded-l px-4 py-2 focus:outline-none"
placeholder="Type your message..."
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyPress={(e) => {
if (e.key === "Enter") onSend();
}}
/>
Send
);
}
export default ChatWindow;
CodeSidebar.js:
import React from "react";
import { FaTimes } from "react-icons/fa";
function CodeSidebar({ code, onClose }) {
return (
Code Snippet
{code}
);
}
export default CodeSidebar;
Header.js:
import React from "react";
import { FaRobot } from "react-icons/fa";
function Header() {
const getGreeting = () => {
const hour = new Date().getHours();
if (hour < 12) return "Good Morning";
if (hour < 18) return "Good Afternoon";
return "Good Evening";
};
return (
{getGreeting()}
);
}
Sidebar.js:
import React from 'react';
import { FaPlus, FaHistory } from 'react-icons/fa';
import { useDispatch } from 'react-redux';
import { setActiveChat, startNewChat } from '../redux/chatSlice';
function Sidebar({ chats, activeChat }) {
const dispatch = useDispatch();
const handleNewChat = () => {
dispatch(startNewChat());
};
const handleSetActiveChat = (index) => {
dispatch(setActiveChat(index));
};
return (
Chats
{chats.length === 0 ? (
No chats yet. Start a new chat!
) : (
chats.map((chat, index) => (
<div
key={index}
onClick={() => handleSetActiveChat(index)}
className={p-4 cursor-pointer hover:bg-gray-100 ${ activeChat === index ? 'bg-gray-200' : '' } flex items-center justify-between}
>
Chat {index + 1}
))
)}
);
}
chatSlice.js:
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';
// Async thunk for sending messages
export const sendMessage = createAsyncThunk(
'chat/sendMessage',
async ({ text, activeChat }, { rejectWithValue }) => {
try {
const response = await axios.post('http://localhost:8000/api/chat ', { text });
console.log('Response from backend:', response.data.response); // Debug log
return { response: response.data.response, activeChat };
} catch (error) {
console.error('Error in sendMessage thunk:', error);
return rejectWithValue('Error sending message');
}
}
);
const chatSlice = createSlice({
name: 'chat',
initialState: {
chats: [],
activeChat: null,
codeSnippet: null,
commonQueries: [
"What's the weather today?",
'Tell me a joke',
'Show me a React example',
],
status: 'idle', // 'idle' | 'loading' | 'succeeded' | 'failed'
error: null,
},
reducers: {
startNewChat: (state) => {
state.activeChat = null;
state.codeSnippet = null;
// Optional: Reset input if it's part of Redux state
},
setActiveChat: (state, action) => {
state.activeChat = action.payload;
state.codeSnippet = null;
},
setCodeSnippet: (state, action) => {
state.codeSnippet = action.payload;
},
// If you plan to manage input globally, you can add a reducer here
// setInput: (state, action) => {
// state.input = action.payload;
// },
},
extraReducers: (builder) => {
builder
.addCase(sendMessage.pending, (state) => {
state.status = 'loading';
})
.addCase(sendMessage.fulfilled, (state, action) => {
const { response, activeChat } = action.payload;
let chatIndex = activeChat;
code Copy code
if (activeChat === null) {
// Starting a new chat
state.chats.push([]);
chatIndex = state.chats.length - 1;
state.activeChat = chatIndex;
}
// Extract code if present using RegExp
// Ensure 'response' is a string before calling 'match'
let codeMatch = null;
if (typeof response === 'string') {
}
console.log('Code Match:', codeMatch); // Debug log
let botMessage = { sender: 'bot', text: response };
if (codeMatch && codeMatch[1]) {
const code = codeMatch[1];
botMessage = { sender: 'bot', text: response, isCode: true, code };
}
// Initialize chat array if undefined (precaution)
if (!state.chats[chatIndex]) {
state.chats[chatIndex] = [];
}
// Add bot message to the chat
state.chats[chatIndex].push(botMessage);
state.status = 'succeeded';
})
.addCase(sendMessage.rejected, (state, action) => {
state.status = 'failed';
state.error = action.payload;
if (state.activeChat !== null) {
// Ensure the active chat exists
if (!state.chats[state.activeChat]) {
state.chats[state.activeChat] = [];
}
state.chats[state.activeChat].push({
sender: 'bot',
text: 'Sorry, something went wrong.',
});
}
});
export const { startNewChat, setActiveChat, setCodeSnippet } = chatSlice.actions;
export default chatSlice.reducer;
store.js:
import { configureStore } from '@reduxjs/toolkit';
import chatReducer from './chatSlice';
const store = configureStore({
reducer: {
chat: chatReducer,
},
});
Certainly! I'll go through each of your provided files, identify the errors, and provide corrected versions along with explanations. This comprehensive approach ensures your React chatbot application functions smoothly.
1. App.js
Issues Identified:
Incorrect JSX Comments: In React, comments within JSX should be wrapped using {/* ... */} instead of {/ ... /}.
Unused input from Redux State: The input property is destructured from Redux state but isn't defined in your chatSlice. Since you're managing input locally using React's useState, this should be removed.
Deprecated onKeyPress Event: While not breaking, onKeyPress is deprecated. It's better to use onKeyDown or onKeyUp.
Missing Dependency in useEffect: If you intend to handle side effects when status or error changes, ensure all dependencies are correctly listed.
Corrected App.js:
javascript Copy code
import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import Sidebar from './components/Sidebar';
import Header from './components/Header';
import ChatWindow from './components/ChatWindow';
import CodeSidebar from './components/CodeSidebar';
import { FaSearch } from 'react-icons/fa';
import {
sendMessage as sendMessageAction,
startNewChat,
setCodeSnippet,
} from './redux/chatSlice';
function App() {
const dispatch = useDispatch();
const {
chats,
activeChat,
codeSnippet,
commonQueries,
status,
error,
} = useSelector((state) => state.chat);
const [localInput, setLocalInput] = React.useState('');
// Handle sending a message
const sendMessage = () => {
if (localInput.trim() === '') return;
// Dispatch sendMessage async thunk
dispatch(sendMessageAction({ text: localInput, activeChat }));
setLocalInput('');
};
// Start a new chat
const handleStartNewChat = () => {
dispatch(startNewChat());
};
// Handle code click
const handleCodeClick = (code) => {
dispatch(setCodeSnippet(code));
};
// Optionally, handle error state
useEffect(() => {
if (status === 'failed') {
console.error(error);
}
}, [status, error]);
return (
<div className="flex h-screen">
{/* Sidebar */}
<Sidebar chats={chats} activeChat={activeChat} />
{/* Main Content */}
<div className="flex-1 flex flex-col">
{/* Header */}
<Header />
{/* Search Box and Common Queries (Visible when no active chat) */}
{activeChat === null && (
<div className="p-4 bg-gray-100">
{/* Search Box */}
<div className="flex mb-4">
<input
type="text"
className="flex-grow border rounded-l px-4 py-2 focus:outline-none"
placeholder="Enter your query..."
value={localInput}
onChange={(e) => setLocalInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') sendMessage();
}}
/>
<button
className="bg-blue-500 text-white px-4 py-2 rounded-r hover:bg-blue-600"
onClick={sendMessage}
>
<FaSearch />
</button>
</div>
{/* Common Queries */}
<div>
<h3 className="text-lg font-semibold mb-2">Common Queries:</h3>
<div className="flex flex-wrap gap-2">
{commonQueries.map((query, index) => (
<button
key={index}
className="bg-gray-200 text-gray-800 px-3 py-1 rounded hover:bg-gray-300"
onClick={() => setLocalInput(query)}
>
{query}
</button>
))}
</div>
</div>
</div>
)}
{/* Chat Window (Visible when a chat is active) */}
{activeChat !== null && (
<ChatWindow
messages={chats[activeChat]}
onSend={sendMessage}
input={localInput}
setInput={setLocalInput}
onCodeClick={handleCodeClick}
/>
)}
</div>
{/* Code Sidebar */}
{codeSnippet && (
<CodeSidebar onClose={() => dispatch(setCodeSnippet(null))} code={codeSnippet} />
)}
</div>
);
}
export default App;
Summary of Changes:
JSX Comments: Replaced all incorrect comment syntax { / ... / } with {/* ... */}.
Removed Unused input: Removed input from the destructured Redux state since it's managed locally.
Updated Event Handler: Changed onKeyPress to onKeyDown for better compatibility and to adhere to React's latest standards.
2. index.js
Issues Identified:
Deprecated ReactDOM.render Method: With React 18, ReactDOM.render is deprecated. The recommended approach is to use ReactDOM.createRoot.
Corrected index.js:
javascript Copy code
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import store from './redux/store'; // Import the store
import { Provider } from 'react-redux'; // Import Provider
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);
Summary of Changes:
Updated to React 18 Syntax: Switched from ReactDOM.render to using ReactDOM.createRoot and root.render as per React 18 guidelines.
3. ChatWindow.js
Issues Identified:
Deprecated onKeyPress Event: Similar to App.js, onKeyPress is deprecated. It's advisable to switch to onKeyDown or onKeyUp.
Corrected ChatWindow.js:
javascript Copy code
import React, { useRef, useEffect } from "react";
import { FaCopy } from "react-icons/fa";
function ChatWindow({ messages, onSend, input, setInput, onCodeClick }) {
const messagesEndRef = useRef(null);
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
};
useEffect(scrollToBottom, [messages]);
return (
<div className="flex flex-col flex-1">
<div className="flex-1 overflow-y-auto p-4 bg-gray-50">
{messages.map((msg, index) => (
<div
key={index}
className={`mb-4 flex ${
msg.sender === "user" ? "justify-end" : "justify-start"
}`}
>
<div
className={`px-4 py-2 rounded-lg max-w-xs ${
msg.sender === "user"
? "bg-blue-500 text-white"
: "bg-white text-gray-800 shadow"
}`}
onClick={() => {
if (msg.isCode && onCodeClick) onCodeClick(msg.code);
}}
>
{msg.isCode ? (
<pre className="whitespace-pre-wrap cursor-pointer">
{msg.code.length > 100
? `${msg.code.substring(0, 100)}...`
: msg.code}
{msg.code.length > 100 && (
<span className="text-blue-300"> Click to expand</span>
)}
</pre>
) : (
msg.text
)}
</div>
</div>
))}
<div ref={messagesEndRef} />
</div>
<div className="flex p-4 bg-white border-t">
<input
type="text"
className="flex-grow border rounded-l px-4 py-2 focus:outline-none"
placeholder="Type your message..."
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") onSend();
}}
/>
<button
className="bg-blue-500 text-white px-4 py-2 rounded-r hover:bg-blue-600"
onClick={onSend}
>
Send
</button>
</div>
</div>
);
}
export default ChatWindow;
Summary of Changes:
Updated Event Handler: Changed onKeyPress to onKeyDown in the input element to align with React's current standards.
4. CodeSidebar.js
Issues Identified:
No Immediate Errors Detected: The component seems well-structured and functional.
Accessibility Considerations: For better accessibility, it's good practice to add aria-label to buttons, especially those with icons.
Recommended Enhancements:
While there are no outright errors, enhancing accessibility is beneficial.
Enhanced CodeSidebar.js:
javascript Copy code
import React from "react";
import { FaTimes } from "react-icons/fa";
function CodeSidebar({ code, onClose }) {
return (
<div className="fixed top-0 right-0 w-1/3 h-full bg-gray-100 shadow-lg p-4 overflow-y-auto">
<div className="flex justify-between items-center mb-4">
<h2 className="text-xl font-semibold">Code Snippet</h2>
<button onClick={onClose} aria-label="Close Code Sidebar">
<FaTimes size={20} />
</button>
</div>
<pre className="bg-white p-4 rounded shadow overflow-auto">
<code>{code}</code>
</pre>
</div>
);
}
export default CodeSidebar;
Summary of Changes:
Accessibility Addition: Added aria-label to the close button to assist screen readers.
5. Header.js
Issues Identified:
No Immediate Errors Detected: The component correctly displays a greeting based on the current time.
No Changes Needed:
If desired, for consistency and accessibility, you can enhance the component slightly.
Enhanced Header.js (Optional):
javascript Copy code
import React from "react";
import { FaRobot } from "react-icons/fa";
function Header() {
const getGreeting = () => {
const hour = new Date().getHours();
if (hour < 12) return "Good Morning";
if (hour < 18) return "Good Afternoon";
return "Good Evening";
};
return (
<div className="flex items-center justify-between p-4 bg-white shadow-md">
<div className="flex items-center">
<FaRobot size={30} className="text-blue-500 mr-2" aria-hidden="true" />
<h1 className="text-2xl font-bold">{getGreeting()}</h1>
</div>
</div>
);
}
export default Header;
Summary of Changes:
Accessibility Enhancement: Added aria-hidden="true" to the robot icon since it's decorative.
6. Sidebar.js
Issues Identified:
No Immediate Errors Detected: The component correctly displays the list of chats and allows starting a new chat.
Key Usage: Using the index as a key in lists can lead to issues if the list order changes. It's better to use a unique identifier if available.
Corrected Sidebar.js:
Assuming each chat has a unique identifier (e.g., id), it's preferable to use that. If not, and the list doesn't change order, using the index is acceptable.
javascript Copy code
import React from 'react';
import { FaPlus, FaHistory } from 'react-icons/fa';
import { useDispatch } from 'react-redux';
import { setActiveChat, startNewChat } from '../redux/chatSlice';
function Sidebar({ chats, activeChat }) {
const dispatch = useDispatch();
const handleNewChat = () => {
dispatch(startNewChat());
};
const handleSetActiveChat = (index) => {
dispatch(setActiveChat(index));
};
return (
<div className="w-64 bg-white shadow-md h-screen flex flex-col">
<div className="flex items-center justify-between p-4 border-b">
<h2 className="text-xl font-semibold">Chats</h2>
<button
onClick={handleNewChat}
className="text-blue-500 hover:text-blue-700"
title="New Chat"
aria-label="Start a new chat"
>
<FaPlus size={20} />
</button>
</div>
<div className="flex-1 overflow-y-auto">
{chats.length === 0 ? (
<p className="p-4 text-gray-500">No chats yet. Start a new chat!</p>
) : (
chats.map((chat, index) => (
<div
key={index} // Ideally, use a unique identifier like `chat.id`
onClick={() => handleSetActiveChat(index)}
className={`p-4 cursor-pointer hover:bg-gray-100 ${
activeChat === index ? 'bg-gray-200' : ''
} flex items-center justify-between`}
>
<span>Chat {index + 1}</span>
<FaHistory size={14} className="text-gray-500" aria-hidden="true" />
</div>
))
)}
</div>
</div>
);
}
export default Sidebar;
Summary of Changes:
Accessibility Addition: Added aria-label to the "New Chat" button.
Icon Accessibility: Added aria-hidden="true" to decorative icons.
Key Usage Note: Highlighted the recommendation to use unique identifiers for keys instead of indices.
7. chatSlice.js
Issues Identified:
Incomplete Code Extraction Logic: The sendMessage.fulfilled case has an incomplete if block for extracting code from the response.
Potential State Mutation: While createSlice uses Immer.js for immutability, ensure that any complex state manipulations don't inadvertently cause issues.
Missing Return Value in sendMessage.fulfilled (Not Applicable): The createAsyncThunk handles return values appropriately, so no issues here.
Corrected chatSlice.js:
Summary of Changes:
Implemented Code Extraction: Added a regular expression to extract code snippets wrapped within triple backticks from the response.
javascript Copy code
codeMatch = response.match(/```([\s\S]*?)```/);
Explanation: This regex captures any content between and, allowing the application to identify and handle code snippets separately.
Comments and Clarifications: Added comments to explain the purpose of different sections for better readability and maintainability.
8. store.js
Issues Identified:
No Immediate Errors Detected: The store configuration using Redux Toolkit appears correct.
No Changes Needed:
However, for better scalability and debugging, you might consider adding middleware or integrating Redux DevTools.
Enhanced store.js (Optional):
javascript Copy code
import { configureStore } from '@reduxjs/toolkit';
import chatReducer from './chatSlice';
const store = configureStore({
reducer: {
chat: chatReducer,
},
// The following middleware and devTools settings are optional
// middleware: (getDefaultMiddleware) =>
// getDefaultMiddleware({
// serializableCheck: false,
// }),
// devTools: process.env.NODE_ENV !== 'production',
});
export default store;
Summary of Changes:
Scalability Consideration: Commented out sections show how you can customize middleware or conditionally enable Redux DevTools.
Final Recommendations
Consistent Styling: Ensure that all components follow a consistent styling pattern, especially if using utility-first frameworks like Tailwind CSS.
Accessibility: Continuously enhance accessibility by adding appropriate aria attributes and ensuring all interactive elements are keyboard navigable.
Error Handling: Consider enhancing error handling to provide user-friendly error messages within the UI, not just logging to the console.
Code Splitting: For performance optimization, consider code splitting larger components or using React's lazy and Suspense for dynamic imports.
Testing: Implement unit and integration tests to ensure each component behaves as expected, especially after making these corrections.
By addressing the above corrections and recommendations, your React chatbot application should function more reliably and offer a better user experience.
Show full message · 599 lines Copy first response
Not yet included in a published release.
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';
// Async thunk for sending messages
export const sendMessage = createAsyncThunk(
'chat/sendMessage',
async ({ text, activeChat }, { rejectWithValue }) => {
try {
const response = await axios.post('http://localhost:8000/api/chat', { text });
console.log('Response from backend:', response.data.response); // Debug log
return { response: response.data.response, activeChat };
} catch (error) {
console.error('Error in sendMessage thunk:', error);
return rejectWithValue('Error sending message');
}
}
);
const chatSlice = createSlice({
name: 'chat',
initialState: {
chats: [], // Array of chat arrays
activeChat: null, // Index of the active chat
codeSnippet: null, // Currently selected code snippet
commonQueries: [
"What's the weather today?",
'Tell me a joke',
'Show me a React example',
],
status: 'idle', // 'idle' | 'loading' | 'succeeded' | 'failed'
error: null, // Error message
},
reducers: {
startNewChat: (state) => {
state.activeChat = null;
state.codeSnippet = null;
// Optionally, you can initialize a new chat here
},
setActiveChat: (state, action) => {
state.activeChat = action.payload;
state.codeSnippet = null;
},
setCodeSnippet: (state, action) => {
state.codeSnippet = action.payload;
},
// If you plan to manage input globally, you can add a reducer here
// setInput: (state, action) => {
// state.input = action.payload;
// },
},
extraReducers: (builder) => {
builder
.addCase(sendMessage.pending, (state) => {
state.status = 'loading';
})
.addCase(sendMessage.fulfilled, (state, action) => {
const { response, activeChat } = action.payload;
let chatIndex = activeChat;
if (activeChat === null) {
// Starting a new chat
state.chats.push([]);
chatIndex = state.chats.length - 1;
state.activeChat = chatIndex;
}
// Extract code if present using RegExp
// Ensure 'response' is a string before calling 'match'
let codeMatch = null;
if (typeof response === 'string') {
// Example regex to extract code blocks wrapped in triple backticks
codeMatch = response.match(/```([\s\S]*?)```/);
}
console.log('Code Match:', codeMatch); // Debug log
let botMessage = { sender: 'bot', text: response };
if (codeMatch && codeMatch[1]) {
const code = codeMatch[1];
botMessage = { sender: 'bot', text: response, isCode: true, code };
}
// Initialize chat array if undefined (precaution)
if (!state.chats[chatIndex]) {
state.chats[chatIndex] = [];
}
// Add bot message to the chat
state.chats[chatIndex].push(botMessage);
state.status = 'succeeded';
})
.addCase(sendMessage.rejected, (state, action) => {
state.status = 'failed';
state.error = action.payload;
if (state.activeChat !== null) {
// Ensure the active chat exists
if (!state.chats[state.activeChat]) {
state.chats[state.activeChat] = [];
}
state.chats[state.activeChat].push({
sender: 'bot',
text: 'Sorry, something went wrong.',
});
}
});
},
});
export const { startNewChat, setActiveChat, setCodeSnippet } = chatSlice.actions;
export default chatSlice.reducer;