From 2d72f0ef1214aa0566901d12ac47dff5427c270c Mon Sep 17 00:00:00 2001 From: KOSASIH Date: Wed, 7 Aug 2024 22:32:15 +0700 Subject: [PATCH] Update ChatWindow.js --- .../client/components/ChatWindow.js | 44 +++++++++++++++---- 1 file changed, 36 insertions(+), 8 deletions(-) diff --git a/projects/PiWalletBot/client/components/ChatWindow.js b/projects/PiWalletBot/client/components/ChatWindow.js index 88cf3e4de..0db71f039 100644 --- a/projects/PiWalletBot/client/components/ChatWindow.js +++ b/projects/PiWalletBot/client/components/ChatWindow.js @@ -1,11 +1,15 @@ import React, { useState, useEffect } from 'react'; import { Dialogflow } from '@google-cloud/dialogflow'; import { useApi } from '../context/api'; +import { useAuth } from '../context/auth'; const ChatWindow = () => { const [messages, setMessages] = useState([]); const [inputValue, setInputValue] = useState(''); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(null); const api = useApi(); + const auth = useAuth(); useEffect(() => { const dialogflow = new Dialogflow(); @@ -26,24 +30,46 @@ const ChatWindow = () => { setInputValue(event.target.value); }; - const handleSendMessage = () => { + const handleSendMessage = async () => { const message = inputValue.trim(); if (message) { setInputValue(''); - handleSendMessage(message); + try { + setLoading(true); + const response = await dialogflow.detectIntent(message); + setMessages((prevMessages) => [...prevMessages, response]); + setLoading(false); + } catch (error) { + setError(error.message); + setLoading(false); + } } }; const handleGetBalance = async () => { - const balance = await api.getPiBalance(); - setMessages((prevMessages) => [...prevMessages, `Your balance is ${balance} Pi coins`]); + try { + setLoading(true); + const balance = await api.getPiBalance(auth.user.address); + setMessages((prevMessages) => [...prevMessages, `Your balance is ${balance} Pi coins`]); + setLoading(false); + } catch (error) { + setError(error.message); + setLoading(false); + } }; const handleSendTransaction = async () => { - const amount = 10; // hardcoded for demo purposes - const recipient = 'recipient_address'; // hardcoded for demo purposes - const transaction = await api.sendPiTransaction(amount, recipient); - setMessages((prevMessages) => [...prevMessages, `Transaction sent: ${transaction}`]); + try { + setLoading(true); + const amount = 10; // hardcoded for demo purposes + const recipient = 'recipient_address'; // hardcoded for demo purposes + const transaction = await api.sendPiTransaction(auth.user.address, recipient, amount); + setMessages((prevMessages) => [...prevMessages, `Transaction sent: ${transaction}`]); + setLoading(false); + } catch (error) { + setError(error.message); + setLoading(false); + } }; return ( @@ -63,6 +89,8 @@ const ChatWindow = () => { + {loading ?

Loading...

: null} + {error ?

Error: {error}

: null} ); };