added suspense for home page

This commit is contained in:
2024-02-02 10:12:10 +01:00
parent e66958f6a3
commit 3cb93c53c4
4 changed files with 131 additions and 76 deletions

View File

@@ -1,12 +1,7 @@
import { AddLocationButton } from './ui/AddLocationButton';
import { PageFooter } from './ui/PageFooter';
import { fetchAllLocations } from './lib/actions/locationActions';
import { fetchAvailableYears } from './lib/actions/monthActions';
import { BillingLocation, YearMonth } from './lib/db-types';
import { FC } from 'react';
import { FC, Suspense } from 'react';
import { Main } from './ui/Main';
import { MonthCard } from './ui/MonthCard';
import { MonthLocationList } from './ui/MonthLocationList';
import HomePage from './ui/HomePage';
import { HomePageSkeleton } from './ui/MonthCardSceleton';
export interface PageProps {
searchParams?: {
@@ -17,74 +12,11 @@ export interface PageProps {
const Page:FC<PageProps> = async ({ searchParams }) => {
let availableYears: number[];
try {
availableYears = await fetchAvailableYears();
} catch (error:any) {
return (
<main className="flex min-h-screen flex-col p-6 bg-base-300">
<p className="text-center text-2xl text-red-500">{error.message}</p>
</main>);
}
// if the database is in it's initial state, show the add location button for the current month
if(availableYears.length === 0) {
const currentYearMonth:YearMonth = {
year: new Date().getFullYear(),
month: new Date().getMonth() + 1
};
return (
<main className="flex min-h-screen flex-col p-6 bg-base-300">
<MonthCard yearMonth={currentYearMonth} key={`month-${currentYearMonth}`} monthlyExpense={0}>
<AddLocationButton yearMonth={currentYearMonth} />
</MonthCard>
<PageFooter />
</main>
);
}
const currentYear = Number(searchParams?.year) || availableYears[0];
const locations = await fetchAllLocations(currentYear);
// group locations by month
const months = locations.reduce((acc, location) => {
const {year, month} = location.yearMonth;
const key = `${year}-${month}`;
const locationsInMonth = acc[key];
if(locationsInMonth) {
return({
...acc,
[key]: {
yearMonth: location.yearMonth,
locations: [...locationsInMonth.locations, location],
monthlyExpense: locationsInMonth.monthlyExpense + location.bills.reduce((acc, bill) => bill.paid ? acc + (bill.payedAmount ?? 0) : acc, 0)
}
})
}
return({
...acc,
[key]: {
yearMonth: location.yearMonth,
locations: [location],
monthlyExpense: location.bills.reduce((acc, bill) => bill.paid ? acc + (bill.payedAmount ?? 0) : acc, 0)
}
});
}, {} as {[key:string]:{
yearMonth: YearMonth,
locations: BillingLocation[],
monthlyExpense: number
} });
return (
<Main>
<MonthLocationList availableYears={availableYears} months={months} />
<Suspense fallback={<HomePageSkeleton />}>
<HomePage searchParams={searchParams} />
</Suspense>
</Main>
);
}