made hook to streamline getting totals and expense by type of category
This commit is contained in:
parent
85e92c85b4
commit
7a5ace403e
6 changed files with 233 additions and 176 deletions
33
hooks/useCategoryData.ts
Normal file
33
hooks/useCategoryData.ts
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
import { useState, useEffect } from 'react';
|
||||
import useFetch from './useFetch';
|
||||
import { CategoryType } from '../services/database';
|
||||
|
||||
export const useCategoryData = (CategoryType: string) => {
|
||||
const [data, setData] = useState({ total: 0, expenseTotal: 0 });
|
||||
const [isLoading, setLoading] = useState(true);
|
||||
|
||||
const categoryQuery = {
|
||||
sql: `SELECT SUM(allocated_amount) as total FROM category WHERE type = '${CategoryType.toString()}'`,
|
||||
args: []
|
||||
};
|
||||
|
||||
const expenseQuery = {
|
||||
sql: `SELECT SUM(e.amount) as total FROM expense e JOIN category c ON e.category_guid = c.guid WHERE c.type = '${CategoryType.toString()}'`,
|
||||
args: []
|
||||
};
|
||||
|
||||
const { data: categoryData, isLoading: categoryLoading } = useFetch(categoryQuery);
|
||||
const { data: expenseData, isLoading: expenseLoading } = useFetch(expenseQuery);
|
||||
|
||||
useEffect(() => {
|
||||
if (categoryData && expenseData) {
|
||||
setData({
|
||||
total: categoryData[0]?.total || 0,
|
||||
expenseTotal: expenseData[0]?.total || 0
|
||||
});
|
||||
}
|
||||
setLoading(categoryLoading || expenseLoading);
|
||||
}, [categoryData, categoryLoading, expenseData, expenseLoading]);
|
||||
|
||||
return { categoryData, expenseData, isLoading, data };
|
||||
};
|
||||
Reference in a new issue