Problem:
Despite successful data fetching and processing, the chats do not appear in the UI. Could someone point out what might be going wrong or suggest any debugging steps?
I’m working on a web app where I fetch Q&A chat history from a Cloud Firestore database and display it on the frontend. The chats are retrieved successfully (confirmed via Network tab in browser dev tools), but they are not displayed in my app.
Backend Code:
I have a Flask endpoint to fetch chat history:
@application.route('/chat-history', methods=['POST'])
def get_user_chat_history():
user_id = request.json['user_id']
document_id = request.json['document_id']
if not user_id or not document_id:
return jsonify({"error": "Missing required parameters: user and document"}), 400
user_chats_ref = db.collection("ChatHistory").document(user_id).collection(str(document_id)).document("chats")
try:
chat_doc = user_chats_ref.get()
if not chat_doc.exists:
return jsonify({"error": "No chat history found"}), 404
chat_data = chat_doc.to_dict()
chat_array = chat_data.get('chat', [])
sorted_chat_array = sorted(chat_array, key=lambda x: float(x['timestamp']), reverse=True)
return jsonify(sorted_chat_array), 200
except Exception as e:
print(f'Error fetching chat history for user {user_id}: {e}')
return jsonify({"error": "Error fetching chat history"}), 500
Frontend Code (React):
Here’s the React code where I attempt to display the fetched chats:
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged((user) => {
if (!user) {
navigate("/login");
}
});
populateChat();
return () => unsubscribe();
}, []);
async function populateChat() {
const response = await fetch(`${baseurl}/chat-history`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
user_id: uid,
document_id: profileName,
}),
});
try {
const data = await response.json();
const transformData = (data) => {
const transformed = [];
data.forEach((item) => {
for (const key in item) {
item[key].forEach((entry) => {
if (entry.question) {
transformed.push({ user: "user", message: entry.question });
}
if (entry.answer) {
transformed.push({ user: "bot", message: entry.answer });
}
});
}
});
return transformed;
};
const transformedData = transformData(data);
const firstFiveTexts = transformedData.slice(0, 6);
// Assuming you are setting the state somewhere here to update the UI with firstFiveTexts
} catch (error) {
console.error('Error fetching chat history:', error);
}
}
What I’ve Tried:
- Verified that the backend returns the correct data structure.
- Confirmed data fetch success through the browser’s Network tab.
- Ensured that populateChat function runs and processes the data.
user26341400 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.