From 179306ac43e6e396f950108d6e4fc5f3f0496c80 Mon Sep 17 00:00:00 2001 From: KOSASIH Date: Wed, 7 Aug 2024 23:06:15 +0700 Subject: [PATCH] Create useWallet.js --- projects/PiWalletBot/hooks/useWallet.js | 64 +++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 projects/PiWalletBot/hooks/useWallet.js diff --git a/projects/PiWalletBot/hooks/useWallet.js b/projects/PiWalletBot/hooks/useWallet.js new file mode 100644 index 000000000..393e4f765 --- /dev/null +++ b/projects/PiWalletBot/hooks/useWallet.js @@ -0,0 +1,64 @@ +import { useState, useEffect } from 'react'; +import { useApi } from './useApi'; +import { useAuth } from './useAuth'; + +const useWallet = () => { + const [balance, setBalance] = useState(0); + const [transactions, setTransactions] = useState([]); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(null); + const api = useApi(); + const { user, token } = useAuth(); + + useEffect(() => { + const getBalance = async () => { + try { + setLoading(true); + const response = await api.get('/pi/balance', { headers: { Authorization: `Bearer ${token}` } }); + setBalance(response.data); + } catch (error) { + setError(error); + } finally { + setLoading(false); + } + }; + if (user) { + getBalance(); + } + }, [user, token]); + + useEffect(() => { + const getTransactions = async () => { + try { + setLoading(true); + const response = await api.get('/pi/transactions', { headers: { Authorization: `Bearer ${token}` } }); + setTransactions(response.data); + } catch (error) { + setError(error); + } finally { + setLoading(false); + } finally { + setLoading(false); + } + }; + if (user) { + getTransactions(); + } + }, [user, token]); + + const sendTransaction = async (recipient, amount) => { + try { + setLoading(true); + const response = await api.post('/pi/transactions', { recipient, amount }, { headers: { Authorization: `Bearer ${token}` } }); + setTransactions([...transactions, response.data]); + } catch (error) { + setError(error); + } finally { + setLoading(false); + } + }; + + return { balance, transactions, loading, error, getBalance, getTransactions, sendTransaction }; +}; + +export default useWallet;