import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Bar } from 'react-chartjs-2';
import { Chart as ChartJS, CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend } from 'chart.js';
ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend);
const Home = () => {
const [allocations, setAllocations] = useState({
essentials: 0,
savings: 0,
selfInvestment: 0,
charity: 0,
emergency: 0,
});
const [expenses, setExpenses] = useState([]);
const [error, setError] = useState('');
const token = localStorage.getItem('token');
useEffect(() => {
const fetchData = async () => {
try {
const [allocationsRes, expensesRes] = await Promise.all([
axios.get('https://backend-rockefeller-finance.onrender.com/api/allocations', {
headers: { Authorization: `Bearer ${token}` },
}),
axios.get('https://backend-rockefeller-finance.onrender.com/api/expenses', {
headers: { Authorization: `Bearer ${token}` },
}),
]);
setAllocations(allocationsRes.data);
setExpenses(expensesRes.data);
} catch (err) {
setError(err.response?.data?.error || 'Lỗi lấy dữ liệu');
}
};
fetchData();
}, [token]);
const handleAllocationChange = async (e) => {
const { name, value } = e.target;
const newAllocations = { ...allocations, [name]: parseFloat(value) || 0 };
try {
await axios.post(
'https://rockefeller-finance-backend.onrender.com/api/allocations',
newAllocations,
{ headers: { Authorization: `Bearer ${token}` } }
);
setAllocations(newAllocations);
} catch (err) {
setError(err.response?.data?.error || 'Lỗi cập nhật phân bổ');
}
};
const chartData = {
labels: ['Thiết yếu', 'Tiết kiệm', 'Đầu tư', 'Từ thiện', 'Khẩn cấp'],
datasets: [
{
label: 'Ngân sách (VND)',
data: [
allocations.essentials,
allocations.savings,
allocations.selfInvestment,
allocations.charity,
allocations.emergency,
],
backgroundColor: 'rgba(75, 192, 192, 0.2)',
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 1,
},
],
};
return (
);
};
export default Home;
Trang chủ
{error &&{error}
}Phân bổ ngân sách
Biểu đồ phân bổ
Chi tiêu gần đây
-
{expenses.map((expense, index) => (
- {expense.date}: {expense.category} - {expense.amount} VND ))}