Skip to content

Commit 0abc327

Browse files
committed
feat: account service hooks
1 parent d52991c commit 0abc327

File tree

2 files changed

+78
-27
lines changed

2 files changed

+78
-27
lines changed

electron/renderer/hooks/accounts.tsx

+78
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
import { sortBy } from 'lodash-es';
2+
import { useCallback, useEffect, useState } from 'react';
3+
import { runInBackground } from '../lib/async/run-in-background.js';
4+
import type { Account } from '../types/game.types.js';
5+
import { usePubSub, useSubscribe } from './pubsub.jsx';
6+
7+
/**
8+
* Returns a list of accounts.
9+
* Automatically refreshes the list when an account is saved or removed.
10+
*/
11+
export const useListAccounts = (): Array<Account> => {
12+
const [accounts, setAccounts] = useState<Array<Account>>([]);
13+
14+
const loadAccounts = useCallback(async () => {
15+
const allAccounts = await window.api.listAccounts();
16+
const sortedAccounts = sortBy(allAccounts, 'accountName');
17+
setAccounts(sortedAccounts);
18+
}, []);
19+
20+
// Reload when told to.
21+
useSubscribe('accounts:reload', async () => {
22+
await loadAccounts();
23+
});
24+
25+
// Reload on first render.
26+
useEffect(() => {
27+
runInBackground(async () => {
28+
await loadAccounts();
29+
});
30+
}, [loadAccounts]);
31+
32+
return accounts;
33+
};
34+
35+
type SaveAccountFn = (options: {
36+
accountName: string;
37+
accountPassword: string;
38+
}) => Promise<void>;
39+
40+
/**
41+
* Provides a function that when called saves an account.
42+
*/
43+
export const useSaveAccount = (): SaveAccountFn => {
44+
const { publish } = usePubSub();
45+
46+
const fn = useCallback<SaveAccountFn>(
47+
async (options): Promise<void> => {
48+
const { accountName, accountPassword } = options;
49+
await window.api.saveAccount({ accountName, accountPassword });
50+
publish('account:saved', { accountName });
51+
publish('accounts:reload');
52+
},
53+
[publish]
54+
);
55+
56+
return fn;
57+
};
58+
59+
type RemoveAccountFn = (options: { accountName: string }) => Promise<void>;
60+
61+
/**
62+
* Provides a function that when called removes an account.
63+
*/
64+
export const useRemoveAccount = (): RemoveAccountFn => {
65+
const { publish } = usePubSub();
66+
67+
const fn = useCallback<RemoveAccountFn>(
68+
async (options): Promise<void> => {
69+
const { accountName } = options;
70+
await window.api.removeAccount({ accountName });
71+
publish('account:removed', { accountName });
72+
publish('accounts:reload');
73+
},
74+
[publish]
75+
);
76+
77+
return fn;
78+
};

electron/renderer/hooks/list-accounts.tsx

-27
This file was deleted.

0 commit comments

Comments
 (0)