From 3eb20bb9add9f10df4d8d78b4651403d0600a432 Mon Sep 17 00:00:00 2001 From: bouzuya Date: Thu, 30 Mar 2023 10:48:55 +0900 Subject: [PATCH] Fix undefined access error --- app/accounts/[id]/settings.tsx | 8 ++++++-- components/AccountContext.tsx | 2 +- lib/account.ts | 13 +++++++++++-- tsconfig.json | 1 + 4 files changed, 19 insertions(+), 5 deletions(-) diff --git a/app/accounts/[id]/settings.tsx b/app/accounts/[id]/settings.tsx index 8c086d7..b45dabd 100644 --- a/app/accounts/[id]/settings.tsx +++ b/app/accounts/[id]/settings.tsx @@ -5,7 +5,11 @@ import { Divider, List, Text } from "react-native-paper"; import { useAccount } from "../../../components/AccountContext"; import { DeleteAccountDialog } from "../../../components/DeleteAccountDialog"; import { Screen } from "../../../components/Screen"; -import { getLastEventId, listCategory } from "../../../lib/account"; +import { + getLastEvent, + getLastEventId, + listCategory, +} from "../../../lib/account"; import { deleteAccountFromLocal } from "../../../lib/account-local-storage"; export default function Settings(): JSX.Element { @@ -58,7 +62,7 @@ export default function Settings(): JSX.Element { diff --git a/components/AccountContext.tsx b/components/AccountContext.tsx index 178fab0..dfc608b 100644 --- a/components/AccountContext.tsx +++ b/components/AccountContext.tsx @@ -51,5 +51,5 @@ export function useAccount( .then((account) => setAccount(account)); } }, deps); - return [accounts[accountId], setAccount]; + return [accounts[accountId] ?? null, setAccount]; } diff --git a/lib/account.ts b/lib/account.ts index 2900032..4e3d6f9 100644 --- a/lib/account.ts +++ b/lib/account.ts @@ -115,9 +115,16 @@ export const deleteTransaction = ( return [applyEvent(self, event), event]; }; +// query +export function getLastEvent(self: Account): AccountEvent { + const lastEvent = self.events[self.events.length - 1]; + if (lastEvent === undefined) throw new Error("assertion error"); + return lastEvent; +} + // query export const getLastEventId = (self: Account): string => { - return self.events[self.events.length - 1].id; + return getLastEvent(self).id; }; // query @@ -136,11 +143,13 @@ export const listCategory = ( export const restoreAccount = (events: AccountEvent[]): Account => { if (events.length === 0) throw new Error("events is empty"); + const firstEvent = events[0]; + if (firstEvent === undefined) throw new Error("assertion error"); return events .slice(1) .reduce( (state, event) => applyEvent(state, event), - applyEvent(null, events[0]) + applyEvent(null, firstEvent) ); }; diff --git a/tsconfig.json b/tsconfig.json index b9567f6..9437926 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,6 +1,7 @@ { "extends": "expo/tsconfig.base", "compilerOptions": { + "noUncheckedIndexedAccess": true, "strict": true } }