Skip to content

Commit

Permalink
Fix undefined access error
Browse files Browse the repository at this point in the history
  • Loading branch information
bouzuya committed Mar 30, 2023
1 parent 76a3ae8 commit 3eb20bb
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 5 deletions.
8 changes: 6 additions & 2 deletions app/accounts/[id]/settings.tsx
Expand Up @@ -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 {
Expand Down Expand Up @@ -58,7 +62,7 @@ export default function Settings(): JSX.Element {
<Divider style={{ width: "100%" }} />
<List.Item
title="Last updated"
description={`${account.events[account.events.length - 1].at}`}
description={`${getLastEvent(account).at}`}
style={{ width: "100%" }}
/>
<Divider style={{ width: "100%" }} />
Expand Down
2 changes: 1 addition & 1 deletion components/AccountContext.tsx
Expand Up @@ -51,5 +51,5 @@ export function useAccount(
.then((account) => setAccount(account));
}
}, deps);
return [accounts[accountId], setAccount];
return [accounts[accountId] ?? null, setAccount];
}
13 changes: 11 additions & 2 deletions lib/account.ts
Expand Up @@ -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
Expand All @@ -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)
);
};

Expand Down
1 change: 1 addition & 0 deletions tsconfig.json
@@ -1,6 +1,7 @@
{
"extends": "expo/tsconfig.base",
"compilerOptions": {
"noUncheckedIndexedAccess": true,
"strict": true
}
}

0 comments on commit 3eb20bb

Please sign in to comment.