Chat State Management
Relevant source files
The following files were used as context for generating this wiki page:
Introduction
Chat State Management in this project provides a centralized mechanism for handling real-time communication between buyers and sellers. It facilitates the creation of conversation threads linked to specific products, manages the delivery of messages, and ensures data persistence across browser sessions using local storage.
This system is built using React's Context API, allowing disparate components—such as product detail pages and message dashboards—to access and modify the global chat state without prop drilling. It serves as the primary interface for user interaction regarding product inquiries and negotiations.
Sources: Front/src/context/ChatContext.jsx:1-5, Front/src/App.js:10-14
Architecture and Provider
The chat system is anchored by the ChatProvider, which wraps the application to provide a global state. The state is initialized by attempting to retrieve a JSON string named 'chats' from the browser's localStorage. If no data is found, it defaults to an empty array.
Sources: Front/src/context/ChatContext.jsx:8-12, Front/src/App.js:11-13
Chat State Flow
The following diagram illustrates how the ChatContext interacts with the UI and Local Storage to maintain state consistency.
The diagram shows the bidirectional flow between the React state and Local Storage, triggered by user actions in UI components like the Product Detail or Messages pages.
Sources: Front/src/context/ChatContext.jsx:9-56
Core Data Structures
Chat Object
A chat session is uniquely identified by a composite ID and contains metadata regarding the participants and the item of interest.
| Field | Type | Description |
|---|---|---|
id | String | Unique identifier formatted as ${buyerId}-${sellerId}-${productId} |
buyerId | String/Number | ID of the user interested in buying |
sellerId | String/Number | ID of the user selling the product |
productId | String/Number | ID of the product the chat is regarding |
messages | Array | A collection of message objects |
createdAt | ISO String | Timestamp of when the chat was initiated |
Sources: Front/src/context/ChatContext.jsx:15-24
Message Object
Individual entries within a chat thread are stored as message objects.
| Field | Type | Description |
|---|---|---|
id | Number | Unique message ID (generated via Date.now()) |
userId | String/Number | ID of the user who sent the message |
content | String | The text content of the message |
timestamp | ISO String | Date and time the message was sent |
Sources: Front/src/context/ChatContext.jsx:45-50, Front/src/pages/Messages.jsx:40-45
Key Logic and Operations
Chat Initialization
Conversations are typically initiated from the ProductDetail page. When a user clicks "Contactar Vendedor", the system checks if a chat already exists between that buyer and seller for that specific product. If not, a new entry is created.
Message Processing
Sending a message involves updating the specific chat object within the global array. The sendMessage function maps through the existing chats, appends the new message to the correct thread, and persists the entire updated array to localStorage.
Sources: Front/src/context/ChatContext.jsx:38-57
Data Retrieval and Filtering
The context provides utility functions to filter chats based on the active user's identity.
getUserChats(userId): Filters the global chat list to return only those where the user is either the buyer or the seller.getChatById(chatId): Retrieves a specific conversation object.
Sources: Front/src/context/ChatContext.jsx:59-67, Front/src/pages/Messages.jsx:20-22
Integration with UI Components
Messages Dashboard
The Messages component utilizes the useChat hook to display the user's active conversations and the message history of the selected chat. It maintains a local copy of the chats to allow for immediate UI updates when a message is sent, synchronized with the global context.
// From Messages.jsx
const handleSendMessage = (e) => {
e.preventDefault();
if (!newMessage.trim() || !selectedChat) return;
// Global state update
sendMessage(selectedChat.id, user.id, newMessage.trim());
// Local state update for immediate feedback
const updatedChats = chats.map(chat => {
if (chat.id === selectedChat.id) {
return {
...chat,
messages: [...chat.messages, {
id: Date.now(),
userId: user.id,
content: newMessage.trim(),
timestamp: new Date().toISOString()
}]
};
}
return chat;
});
setChats(updatedChats);
};
Sources: Front/src/pages/Messages.jsx:34-60
Product Detail Redirection
The ProductDetail component manages the entry point to the chat system. It includes logic to prevent a seller from starting a chat with themselves, instead redirecting them to their existing messages.
Sources: Front/src/pages/productDetail.jsx:23-26
Summary
The Chat State Management system provides a robust, client-side communication framework. By leveraging React Context and Local Storage, it ensures that user conversations are preserved across navigation and page refreshes. The system's tight integration with the product data model allows it to dynamically display relevant product information within the chat interface, facilitating a seamless commerce experience.