Skip to content

A local-first personal finance app

Move redux state to react-query - payees states (#6880)

Joel Jeremy Marquez848eaadb0f60
diff --git a/packages/desktop-client/src/accounts/mutations.ts b/packages/desktop-client/src/accounts/mutations.ts
index e6d353f4d7..cc74939a77 100644
--- a/packages/desktop-client/src/accounts/mutations.ts
+++ b/packages/desktop-client/src/accounts/mutations.ts
@@ -26,7 +26,7 @@ import { accountQueries } from './queries';
import { sync } from '@desktop-client/app/appSlice';
import { useAccounts } from '@desktop-client/hooks/useAccounts';
import { addNotification } from '@desktop-client/notifications/notificationsSlice';
-import { markPayeesDirty } from '@desktop-client/payees/payeesSlice';
+import { payeeQueries } from '@desktop-client/payees';
import { useDispatch, useStore } from '@desktop-client/redux';
import type { AppDispatch } from '@desktop-client/redux/store';
import { setNewTransactions } from '@desktop-client/transactions/transactionsSlice';
@@ -191,9 +191,7 @@ export function useMoveAccountMutation() {
},
onSuccess: () => {
invalidateQueries(queryClient);
- // TODO: Change to a call to queryClient.invalidateQueries
- // once payees have been moved to react-query.
- dispatch(markPayeesDirty());
+ invalidateQueries(queryClient, payeeQueries.lists());
},
onError: error => {
console.error('Error moving account:', error);
@@ -399,9 +397,7 @@ export function useLinkAccountMutation() {
},
onSuccess: () => {
invalidateQueries(queryClient);
- // TODO: Change to a call to queryClient.invalidateQueries
- // once payees have been moved to react-query.
- dispatch(markPayeesDirty());
+ invalidateQueries(queryClient, payeeQueries.lists());
},
onError: error => {
console.error('Error linking account:', error);
@@ -441,9 +437,7 @@ export function useLinkAccountSimpleFinMutation() {
},
onSuccess: () => {
invalidateQueries(queryClient);
- // TODO: Change to a call to queryClient.invalidateQueries
- // once payees have been moved to react-query.
- dispatch(markPayeesDirty());
+ invalidateQueries(queryClient, payeeQueries.lists());
},
onError: error => {
console.error('Error linking account to SimpleFIN:', error);
@@ -485,9 +479,7 @@ export function useLinkAccountPluggyAiMutation() {
},
onSuccess: () => {
invalidateQueries(queryClient);
- // TODO: Change to a call to queryClient.invalidateQueries
- // once payees have been moved to react-query.
- dispatch(markPayeesDirty());
+ invalidateQueries(queryClient, payeeQueries.lists());
},
onError: error => {
console.error('Error linking account to PluggyAI:', error);
diff --git a/packages/desktop-client/src/components/ManageRules.tsx b/packages/desktop-client/src/components/ManageRules.tsx
index 0895db0f31..61395cbcec 100644
--- a/packages/desktop-client/src/components/ManageRules.tsx
+++ b/packages/desktop-client/src/components/ManageRules.tsx
@@ -37,7 +37,6 @@ import {
useSelected,
} from '@desktop-client/hooks/useSelected';
import { pushModal } from '@desktop-client/modals/modalsSlice';
-import { getPayees } from '@desktop-client/payees/payeesSlice';
import { useDispatch } from '@desktop-client/redux';
export type FilterData = {
@@ -135,7 +134,7 @@ export function ManageRules({
query: useMemo(() => q('schedules').select('*'), []),
});
const { data: { list: categories } = { list: [] } } = useCategories();
- const payees = usePayees();
+ const { data: payees } = usePayees();
const { data: accounts = [] } = useAccounts();
const filterData = useMemo(
() => ({
@@ -192,8 +191,6 @@ export function ManageRules({
async function loadData() {
await loadRules();
setLoading(false);
-
- await dispatch(getPayees());
}
if (payeeId) {
diff --git a/packages/desktop-client/src/components/accounts/Account.tsx b/packages/desktop-client/src/components/accounts/Account.tsx
index 0c2f2ea47e..fbf94c0058 100644
--- a/packages/desktop-client/src/components/accounts/Account.tsx
+++ b/packages/desktop-client/src/components/accounts/Account.tsx
@@ -31,6 +31,7 @@ import type {
AccountEntity,
CategoryGroupEntity,
NewRuleEntity,
+ PayeeEntity,
RuleActionEntity,
RuleConditionEntity,
TransactionEntity,
@@ -75,7 +76,7 @@ import {
replaceModal,
} from '@desktop-client/modals/modalsSlice';
import { addNotification } from '@desktop-client/notifications/notificationsSlice';
-import { createPayee, getPayees } from '@desktop-client/payees/payeesSlice';
+import { useCreatePayeeMutation } from '@desktop-client/payees';
import * as queries from '@desktop-client/queries';
import { aqlQuery } from '@desktop-client/queries/aqlQuery';
import { pagedQuery } from '@desktop-client/queries/pagedQuery';
@@ -239,7 +240,7 @@ type AccountInternalProps = {
location: ReturnType<typeof useLocation>;
failedAccounts: ReturnType<typeof useFailedAccounts>;
dateFormat: ReturnType<typeof useDateFormat>;
- payees: ReturnType<typeof usePayees>;
+ payees: PayeeEntity[];
categoryGroups: CategoryGroupEntity[];
hideFraction: boolean;
accountsSyncing: string[];
@@ -249,6 +250,7 @@ type AccountInternalProps = {
onUpdateAccount: (account: AccountEntity) => void;
onUnlinkAccount: (id: AccountEntity['id']) => void;
onSyncAndDownload: (accountId?: AccountEntity['id']) => void;
+ onCreatePayee: (name: PayeeEntity['name']) => Promise<PayeeEntity['id']>;
};
type AccountInternalState = {
@@ -381,7 +383,6 @@ class AccountInternal extends PureComponent<
// Important that any async work happens last so that the
// listeners are set up synchronously
- await this.props.dispatch(getPayees());
await this.fetchTransactions(this.state.filterConditions);
// If there is a pending undo, apply it immediately (this happens
@@ -945,7 +946,7 @@ class AccountInternal extends PureComponent<
onCreatePayee = async (name: string) => {
const trimmed = name.trim();
if (trimmed !== '') {
- return this.props.dispatch(createPayee({ name })).unwrap();
+ return await this.props.onCreatePayee(name);
}
return null;
};
@@ -1966,7 +1967,7 @@ export function Account() {
state => state.transactions.matchedTransactions,
);
const { data: accounts = [] } = useAccounts();
- const payees = usePayees();
+ const { data: payees = [] } = usePayees();
const failedAccounts = useFailedAccounts();
const dateFormat = useDateFormat() || 'MM/dd/yyyy';
const [hideFraction] = useSyncedPref('hideFraction');
@@ -2011,6 +2012,10 @@ export function Account() {
const onSyncAndDownload = (id?: AccountEntity['id']) =>
syncAndDownload({ id });
+ const createPayee = useCreatePayeeMutation();
+ const onCreatePayee = (name: PayeeEntity['name']) =>
+ createPayee.mutateAsync({ name });
+
return (
<SchedulesProvider query={schedulesQuery}>
<SplitsExpandedProvider
@@ -2051,6 +2056,7 @@ export function Account() {
onUpdateAccount={onUpdateAccount}
onUnlinkAccount={onUnlinkAccount}
onSyncAndDownload={onSyncAndDownload}
+ onCreatePayee={onCreatePayee}
/>
</SplitsExpandedProvider>
</SchedulesProvider>
diff --git a/packages/desktop-client/src/components/autocomplete/PayeeAutocomplete.test.tsx b/packages/desktop-client/src/components/autocomplete/PayeeAutocomplete.test.tsx
index 23eff88cbe..897b9ed6b7 100644
--- a/packages/desktop-client/src/components/autocomplete/PayeeAutocomplete.test.tsx
+++ b/packages/desktop-client/src/components/autocomplete/PayeeAutocomplete.test.tsx
@@ -10,8 +10,8 @@ import { PayeeAutocomplete } from './PayeeAutocomplete';
import type { PayeeAutocompleteProps } from './PayeeAutocomplete';
import { AuthProvider } from '@desktop-client/auth/AuthProvider';
-import { useCommonPayees } from '@desktop-client/hooks/usePayees';
-import { TestProviders } from '@desktop-client/mocks';
+import { createTestQueryClient, TestProviders } from '@desktop-client/mocks';
+import { payeeQueries } from '@desktop-client/payees';
const PAYEE_SELECTOR = '[data-testid][role=option]';
const PAYEE_SECTION_SELECTOR = '[data-testid$="-item-group"]';
@@ -65,32 +65,6 @@ function extractPayeesAndHeaderNames(screen: Screen) {
.map(firstOrIncorrect);
}
-function renderPayeeAutocomplete(
- props?: Partial<PayeeAutocompleteProps>,
-): HTMLElement {
- const autocompleteProps = {
- ...defaultProps,
- ...props,
- };
-
- render(
- <TestProviders>
- <AuthProvider>
- <div data-testid="autocomplete-test">
- <PayeeAutocomplete
- {...autocompleteProps}
- onSelect={vi.fn()}
- type="single"
- value={null}
- embedded={false}
- />
- </div>
- </AuthProvider>
- </TestProviders>,
- );
- return screen.getByTestId('autocomplete-test');
-}
-
// Not good, see `Autocomplete.js` for details
function waitForAutocomplete() {
return new Promise(resolve => setTimeout(resolve, 0));
@@ -104,20 +78,43 @@ async function clickAutocomplete(autocomplete: HTMLElement) {
await waitForAutocomplete();
}
-vi.mock('../../hooks/usePayees', () => ({
- useCommonPayees: vi.fn(),
- usePayees: vi.fn().mockReturnValue([]),
-}));
-
function firstOrIncorrect(id: string | null): string {
return id?.split('-', 1)[0] || 'incorrect';
}
describe('PayeeAutocomplete.getPayeeSuggestions', () => {
+ const queryClient = createTestQueryClient();
+
beforeEach(() => {
- vi.mocked(useCommonPayees).mockReturnValue([]);
+ queryClient.setQueryData(payeeQueries.listCommon().queryKey, []);
});
+ function renderPayeeAutocomplete(
+ props?: Partial<PayeeAutocompleteProps>,
+ ): HTMLElement {
+ const autocompleteProps = {
+ ...defaultProps,
+ ...props,
+ };
+
+ render(
+ <TestProviders queryClient={queryClient}>
+ <AuthProvider>
+ <div data-testid="autocomplete-test">
+ <PayeeAutocomplete
+ {...autocompleteProps}
+ onSelect={vi.fn()}
+ type="single"
+ value={null}
+ embedded={false}
+ />
+ </div>
+ </AuthProvider>
+ </TestProviders>,
+ );
+ return screen.getByTestId('autocomplete-test');
+ }
+
test('favorites get sorted alphabetically', async () => {
const autocomplete = renderPayeeAutocomplete();
await clickAutocomplete(autocomplete);
@@ -145,7 +142,7 @@ describe('PayeeAutocomplete.getPayeeSuggestions', () => {
makePayee('Steve'),
makePayee('Tony'),
];
- vi.mocked(useCommonPayees).mockReturnValue([
+ queryClient.setQueryData(payeeQueries.listCommon().queryKey, [
makePayee('Bruce'),
makePayee('Natasha'),
makePayee('Steve'),
@@ -183,7 +180,7 @@ describe('PayeeAutocomplete.getPayeeSuggestions', () => {
makePayee('Steve'),
makePayee('Tony', { favorite: true }),
];
- vi.mocked(useCommonPayees).mockReturnValue([
+ queryClient.setQueryData(payeeQueries.listCommon().queryKey, [
makePayee('Bruce'),
makePayee('Natasha'),
makePayee('Steve'),
diff --git a/packages/desktop-client/src/components/autocomplete/PayeeAutocomplete.tsx b/packages/desktop-client/src/components/autocomplete/PayeeAutocomplete.tsx
index c7824e6bf1..100f79471e 100644
--- a/packages/desktop-client/src/components/autocomplete/PayeeAutocomplete.tsx
+++ b/packages/desktop-client/src/components/autocomplete/PayeeAutocomplete.tsx
@@ -31,12 +31,12 @@ import {
import { ItemHeader } from './ItemHeader';
import { useAccounts } from '@desktop-client/hooks/useAccounts';
-import { useCommonPayees, usePayees } from '@desktop-client/hooks/usePayees';
+import { useCommonPayees } from '@desktop-client/hooks/useCommonPayees';
+import { usePayees } from '@desktop-client/hooks/usePayees';
import {
- createPayee,
getActivePayees,
-} from '@desktop-client/payees/payeesSlice';
-import { useDispatch } from '@desktop-client/redux';
+ useCreatePayeeMutation,
+} from '@desktop-client/payees';
type PayeeAutocompleteItem = PayeeEntity & PayeeItemType;
@@ -347,11 +347,12 @@ export function PayeeAutocomplete({
}: PayeeAutocompleteProps) {
const { t } = useTranslation();
- const commonPayees = useCommonPayees();
- const retrievedPayees = usePayees();
+ const { data: commonPayees } = useCommonPayees();
+ const { data: retrievedPayees = [] } = usePayees();
if (!payees) {
payees = retrievedPayees;
}
+ const createPayeeMutation = useCreatePayeeMutation();
const { data: cachedAccounts = [] } = useAccounts();
if (!accounts) {
@@ -391,14 +392,12 @@ export function PayeeAutocomplete({
showInactivePayees,
]);
- const dispatch = useDispatch();
-
async function handleSelect(idOrIds, rawInputValue) {
if (!clearOnBlur) {
onSelect?.(makeNew(idOrIds, rawInputValue), rawInputValue);
} else {
const create = payeeName =>
- dispatch(createPayee({ name: payeeName })).unwrap();
+ createPayeeMutation.mutateAsync({ name: payeeName });
if (Array.isArray(idOrIds)) {
idOrIds = await Promise.all(
diff --git a/packages/desktop-client/src/components/mobile/payees/MobilePayeeEditPage.tsx b/packages/desktop-client/src/components/mobile/payees/MobilePayeeEditPage.tsx
index 14e7fedcfe..10f22ed86d 100644
--- a/packages/desktop-client/src/components/mobile/payees/MobilePayeeEditPage.tsx
+++ b/packages/desktop-client/src/components/mobile/payees/MobilePayeeEditPage.tsx
@@ -26,7 +26,7 @@ export function MobilePayeeEditPage() {
const { id } = useParams<{ id: string }>();
const dispatch = useDispatch();
const { showUndoNotification } = useUndo();
- const payees = usePayees();
+ const { data: payees = [] } = usePayees();
const [payee, setPayee] = useState<PayeeEntity | null>(null);
const [editedPayeeName, setEditedPayeeName] = useState('');
diff --git a/packages/desktop-client/src/components/mobile/payees/MobilePayeesPage.test.tsx b/packages/desktop-client/src/components/mobile/payees/MobilePayeesPage.test.tsx
index 090f2ab692..bb81036dc1 100644
--- a/packages/desktop-client/src/components/mobile/payees/MobilePayeesPage.test.tsx
+++ b/packages/desktop-client/src/components/mobile/payees/MobilePayeesPage.test.tsx
@@ -8,16 +8,13 @@ import type { PayeeEntity } from 'loot-core/types/models';
import { MobilePayeesPage } from './MobilePayeesPage';
import { useNavigate } from '@desktop-client/hooks/useNavigate';
-import { usePayeeRuleCounts } from '@desktop-client/hooks/usePayeeRuleCounts';
-import { usePayees } from '@desktop-client/hooks/usePayees';
-import { TestProviders } from '@desktop-client/mocks';
+import { createTestQueryClient, TestProviders } from '@desktop-client/mocks';
+import { payeeQueries } from '@desktop-client/payees';
vi.mock('@use-gesture/react', () => ({
useDrag: vi.fn().mockReturnValue(() => ({})),
}));
vi.mock('@desktop-client/hooks/useNavigate');
-vi.mock('@desktop-client/hooks/usePayees');
-vi.mock('@desktop-client/hooks/usePayeeRuleCounts');
const mockPayees: PayeeEntity[] = [
{
@@ -39,25 +36,26 @@ const mockPayees: PayeeEntity[] = [
describe('MobilePayeesPage', () => {
const mockNavigate = vi.fn();
+ const queryClient = createTestQueryClient();
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(useNavigate).mockReturnValue(mockNavigate);
- vi.mocked(usePayees).mockImplementation(() => mockPayees);
- vi.mocked(usePayeeRuleCounts).mockReturnValue({
- ruleCounts: new Map([
+
+ queryClient.setQueryData(payeeQueries.list().queryKey, mockPayees);
+ queryClient.setQueryData(
+ payeeQueries.ruleCounts().queryKey,
+ new Map([
['payee-1', 2],
['payee-2', 0],
]),
- isLoading: false,
- refetch: vi.fn().mockResolvedValue(undefined),
- });
+ );
});
const renderPayeesPage = () => {
return render(
- <TestProviders>
+ <TestProviders queryClient={queryClient}>
<MobilePayeesPage />
</TestProviders>,
);
@@ -156,7 +154,9 @@ describe('MobilePayeesPage', () => {
});
it('handles empty payee list', () => {
- vi.mocked(usePayees).mockReturnValue([]);
+ // Set empty payee list in the cache
+ queryClient.setQueryData(payeeQueries.list().queryKey, []);
+ queryClient.setQueryData(payeeQueries.ruleCounts().queryKey, new Map());
renderPayeesPage();
diff --git a/packages/desktop-client/src/components/mobile/payees/MobilePayeesPage.tsx b/packages/desktop-client/src/components/mobile/payees/MobilePayeesPage.tsx
index 29fc633329..632875391c 100644
--- a/packages/desktop-client/src/components/mobile/payees/MobilePayeesPage.tsx
+++ b/packages/desktop-client/src/components/mobile/payees/MobilePayeesPage.tsx
@@ -18,19 +18,17 @@ import { usePayeeRuleCounts } from '@desktop-client/hooks/usePayeeRuleCounts';
import { usePayees } from '@desktop-client/hooks/usePayees';
import { useUndo } from '@desktop-client/hooks/useUndo';
import { addNotification } from '@desktop-client/notifications/notificationsSlice';
-import { useDispatch, useSelector } from '@desktop-client/redux';
+import { useDispatch } from '@desktop-client/redux';
export function MobilePayeesPage() {
const { t } = useTranslation();
const dispatch = useDispatch();
const navigate = useNavigate();
- const payees = usePayees();
+ const { data: payees = [], isPending } = usePayees();
const { showUndoNotification } = useUndo();
const [filter, setFilter] = useState('');
- const { ruleCounts, isLoading: isRuleCountsLoading } = usePayeeRuleCounts();
- const isLoading = useSelector(
- s => s.payees.isPayeesLoading || s.payees.isCommonPayeesLoading,
- );
+ const { data: ruleCounts = new Map(), isPending: isRuleCountsLoading } =
+ usePayeeRuleCounts();
const filteredPayees: PayeeEntity[] = useMemo(() => {
if (!filter) return payees;
@@ -141,7 +139,7 @@ export function MobilePayeesPage() {
payees={filteredPayees}
ruleCounts={ruleCounts}
isRuleCountsLoading={isRuleCountsLoading}
- isLoading={isLoading}
+ isLoading={isPending}
onPayeePress={handlePayeePress}
onPayeeDelete={handlePayeeDelete}
onPayeeRuleAction={handlePayeeRuleAction}
diff --git a/packages/desktop-client/src/components/mobile/rules/MobileRulesPage.tsx b/packages/desktop-client/src/components/mobile/rules/MobileRulesPage.tsx
index 368b4d3c02..365dc622f5 100644
--- a/packages/desktop-client/src/components/mobile/rules/MobileRulesPage.tsx
+++ b/packages/desktop-client/src/components/mobile/rules/MobileRulesPage.tsx
@@ -41,7 +41,7 @@ export function MobileRulesPage() {
query: useMemo(() => q('schedules').select('*'), []),
});
const { data: { list: categories } = { list: [] } } = useCategories();
- const payees = usePayees();
+ const { data: payees = [] } = usePayees();
const { data: accounts = [] } = useAccounts();
const filterData = useMemo(
() => ({
diff --git a/packages/desktop-client/src/components/mobile/schedules/MobileSchedulesPage.tsx b/packages/desktop-client/src/components/mobile/schedules/MobileSchedulesPage.tsx
index b82f4d0788..cc5360296a 100644
--- a/packages/desktop-client/src/components/mobile/schedules/MobileSchedulesPage.tsx
+++ b/packages/desktop-client/src/components/mobile/schedules/MobileSchedulesPage.tsx
@@ -45,7 +45,7 @@ export function MobileSchedulesPage() {
statuses,
} = useSchedules({ query: schedulesQuery });
- const payees = usePayees();
+ const { data: payees = [] } = usePayees();
const { data: accounts = [] } = useAccounts();
const filterIncludes = (str: string | null | undefined) =>
diff --git a/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx b/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx
index 446c12bbcc..fd4c6ed29d 100644
--- a/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx
+++ b/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx
@@ -1681,7 +1681,7 @@ type TransactionEditProps = Omit<
export const TransactionEdit = (props: TransactionEditProps) => {
const { data: { list: categories } = { list: [] } } = useCategories();
- const payees = usePayees();
+ const { data: payees = [] } = usePayees();
const lastTransaction = useSelector(
state => state.transactions.lastTransaction,
);
diff --git a/packages/desktop-client/src/components/mobile/transactions/TransactionList.tsx b/packages/desktop-client/src/components/mobile/transactions/TransactionList.tsx
index 178d609b5f..0842d06f65 100644
--- a/packages/desktop-client/src/components/mobile/transactions/TransactionList.tsx
+++ b/packages/desktop-client/src/components/mobile/transactions/TransactionList.tsx
@@ -337,7 +337,7 @@ function SelectedTransactionsFloatingActionBar({
const { data: accounts = [] } = useAccounts();
const accountsById = useMemo(() => groupById(accounts), [accounts]);
- const payees = usePayees();
+ const { data: payees = [] } = usePayees();
const payeesById = useMemo(() => groupById(payees), [payees]);
const {
diff --git a/packages/desktop-client/src/components/mobile/transactions/TransactionListItem.tsx b/packages/desktop-client/src/components/mobile/transactions/TransactionListItem.tsx
index 5663531dd1..94370025f8 100644
--- a/packages/desktop-client/src/components/mobile/transactions/TransactionListItem.tsx
+++ b/packages/desktop-client/src/components/mobile/transactions/TransactionListItem.tsx
@@ -89,7 +89,7 @@ export function TransactionListItem({
const { t } = useTranslation();
const { data: { list: categories } = { list: [] } } = useCategories();
- const payee = usePayee(transaction?.payee || '');
+ const { data: payee } = usePayee(transaction?.payee);
const displayPayee = useDisplayPayee({ transaction });
const account = useAccount(transaction?.account || '');
diff --git a/packages/desktop-client/src/components/modals/ImportTransactionsModal/ImportTransactionsModal.tsx b/packages/desktop-client/src/components/modals/ImportTransactionsModal/ImportTransactionsModal.tsx
index 7cade9562d..7d177f6996 100644
--- a/packages/desktop-client/src/components/modals/ImportTransactionsModal/ImportTransactionsModal.tsx
+++ b/packages/desktop-client/src/components/modals/ImportTransactionsModal/ImportTransactionsModal.tsx
@@ -11,6 +11,7 @@ import { styles } from '@actual-app/components/styles';
import { Text } from '@actual-app/components/text';
import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
+import { useQueryClient } from '@tanstack/react-query';
import { send } from 'loot-core/platform/client/connection';
import type { ParseFileOptions } from 'loot-core/server/transactions/import/parse-file';
@@ -49,8 +50,7 @@ import {
import { useCategories } from '@desktop-client/hooks/useCategories';
import { useDateFormat } from '@desktop-client/hooks/useDateFormat';
import { useSyncedPrefs } from '@desktop-client/hooks/useSyncedPrefs';
-import { reloadPayees } from '@desktop-client/payees/payeesSlice';
-import { useDispatch } from '@desktop-client/redux';
+import { payeeQueries } from '@desktop-client/payees';
function getFileType(filepath: string): string {
const m = filepath.match(/\.([^.]*)$/);
@@ -159,9 +159,9 @@ export function ImportTransactionsModal({
onImported,
}) {
const { t } = useTranslation();
+ const queryClient = useQueryClient();
const dateFormat = useDateFormat() || ('MM/dd/yyyy' as const);
const [prefs, savePrefs] = useSyncedPrefs();
- const dispatch = useDispatch();
const { data: { list: categories } = { list: [] } } = useCategories();
const [multiplierAmount, setMultiplierAmount] = useState('');
@@ -656,7 +656,7 @@ export function ImportTransactionsModal({
{
onSuccess: async didChange => {
if (didChange) {
- await dispatch(reloadPayees());
+ queryClient.invalidateQueries(payeeQueries.list());
}
if (onImported) {
diff --git a/packages/desktop-client/src/components/modals/MergeUnusedPayeesModal.tsx b/packages/desktop-client/src/components/modals/MergeUnusedPayeesModal.tsx
index 4e72b2636d..46bae8edd5 100644
--- a/packages/desktop-client/src/components/modals/MergeUnusedPayeesModal.tsx
+++ b/packages/desktop-client/src/components/modals/MergeUnusedPayeesModal.tsx
@@ -30,7 +30,7 @@ export function MergeUnusedPayeesModal({
targetPayeeId,
}: MergeUnusedPayeesModalProps) {
const { t } = useTranslation();
- const allPayees = usePayees();
+ const { data: allPayees = [] } = usePayees();
const modalStack = useSelector(state => state.modals.modalStack);
const isEditingRule = !!modalStack.find(m => m.name === 'edit-rule');
const dispatch = useDispatch();
diff --git a/packages/desktop-client/src/components/modals/PayeeAutocompleteModal.tsx b/packages/desktop-client/src/components/modals/PayeeAutocompleteModal.tsx
index bf8af6c1ec..defc7a862b 100644
--- a/packages/desktop-client/src/components/modals/PayeeAutocompleteModal.tsx
+++ b/packages/desktop-client/src/components/modals/PayeeAutocompleteModal.tsx
@@ -26,7 +26,7 @@ export function PayeeAutocompleteModal({
onClose,
}: PayeeAutocompleteModalProps) {
const { t } = useTranslation();
- const payees = usePayees() || [];
+ const { data: payees = [] } = usePayees();
const { data: accounts = [] } = useAccounts();
const navigate = useNavigate();
diff --git a/packages/desktop-client/src/components/payees/ManagePayeesWithData.tsx b/packages/desktop-client/src/components/payees/ManagePayeesWithData.tsx
index 1d6fe05e15..ca6d6c0044 100644
--- a/packages/desktop-client/src/components/payees/ManagePayeesWithData.tsx
+++ b/packages/desktop-client/src/components/payees/ManagePayeesWithData.tsx
@@ -1,4 +1,6 @@
-import React, { useCallback, useEffect, useState } from 'react';
+import React, { useEffect } from 'react';
+
+import { useQueryClient } from '@tanstack/react-query';
import { listen, send } from 'loot-core/platform/client/connection';
import * as undo from 'loot-core/platform/client/undo';
@@ -9,10 +11,11 @@ import type { NewRuleEntity, PayeeEntity } from 'loot-core/types/models';
import { ManagePayees } from './ManagePayees';
+import { useOrphanedPayees } from '@desktop-client/hooks/useOrphanedPayees';
import { usePayeeRuleCounts } from '@desktop-client/hooks/usePayeeRuleCounts';
import { usePayees } from '@desktop-client/hooks/usePayees';
import { pushModal } from '@desktop-client/modals/modalsSlice';
-import { getPayees, reloadPayees } from '@desktop-client/payees/payeesSlice';
+import { payeeQueries } from '@desktop-client/payees';
import { useDispatch } from '@desktop-client/redux';
type ManagePayeesWithDataProps = {
@@ -22,24 +25,15 @@ type ManagePayeesWithDataProps = {
export function ManagePayeesWithData({
initialSelectedIds,
}: ManagePayeesWithDataProps) {
- const payees = usePayees();
+ const queryClient = useQueryClient();
+ const { data: payees = [], refetch: refetchPayees } = usePayees();
+ const { data: orphanedPayees = [], refetch: refetchOrphanedPayees } =
+ useOrphanedPayees();
const dispatch = useDispatch();
- const { ruleCounts, refetch: refetchRuleCounts } = usePayeeRuleCounts();
-
- const [orphans, setOrphans] = useState<Array<Pick<PayeeEntity, 'id'>>>([]);
-
- const refetchOrphanedPayees = useCallback(async () => {
- const orphs = await send('payees-get-orphaned');
- setOrphans(orphs);
- }, []);
+ const { data: ruleCounts = new Map(), refetch: refetchRuleCounts } =
+ usePayeeRuleCounts();
useEffect(() => {
- async function loadData() {
- await dispatch(getPayees());
- await refetchOrphanedPayees();
- }
- loadData();
-
const unlisten = listen('sync-event', async event => {
if (event.type === 'applied') {
if (event.tables.includes('rules')) {
@@ -51,7 +45,7 @@ export function ManagePayeesWithData({
return () => {
unlisten();
};
- }, [dispatch, refetchRuleCounts, refetchOrphanedPayees]);
+ }, [dispatch, refetchRuleCounts]);
useEffect(() => {
async function onUndo({ tables, messages, meta }: UndoState) {
@@ -115,32 +109,40 @@ export function ManagePayeesWithData({
<ManagePayees
payees={payees}
ruleCounts={ruleCounts}
- orphanedPayees={orphans}
+ orphanedPayees={orphanedPayees}
initialSelectedIds={initialSelectedIds}
onBatchChange={async (changes: Diff<PayeeEntity>) => {
await send('payees-batch-change', changes);
- setOrphans(applyChanges(changes, orphans));
+ queryClient.setQueryData(
+ payeeQueries.listOrphaned().queryKey,
+ existing => applyChanges(changes, existing ?? []),
+ );
}}
onMerge={async ([targetId, ...mergeIds]) => {
await send('payees-merge', { targetId, mergeIds });
- const targetIdIsOrphan = orphans.map(o => o.id).includes(targetId);
+ const targetIdIsOrphan = orphanedPayees
+ .map(o => o.id)
+ .includes(targetId);
const mergeIdsOrphans = mergeIds.filter(m =>
- orphans.map(o => o.id).includes(m),
+ orphanedPayees.map(o => o.id).includes(m),
);
- let filtedOrphans = orphans;
+ let filteredOrphans = orphanedPayees;
if (targetIdIsOrphan && mergeIdsOrphans.length !== mergeIds.length) {
// there is a non-orphan in mergeIds, target can be removed from orphan arr
- filtedOrphans = filtedOrphans.filter(o => o.id !== targetId);
+ filteredOrphans = filteredOrphans.filter(o => o.id !== targetId);
}
- filtedOrphans = filtedOrphans.filter(o => !mergeIds.includes(o.id));
+ filteredOrphans = filteredOrphans.filter(o => !mergeIds.includes(o.id));
// Refetch rule counts after merging
await refetchRuleCounts();
- await dispatch(reloadPayees());
- setOrphans(filtedOrphans);
+ void refetchPayees();
+ queryClient.setQueryData(
+ payeeQueries.listOrphaned().queryKey,
+ filteredOrphans,
+ );
}}
onViewRules={onViewRules}
onCreateRule={onCreateRule}
diff --git a/packages/desktop-client/src/components/reports/reports/Calendar.tsx b/packages/desktop-client/src/components/reports/reports/Calendar.tsx
index 13f0b3767a..cfde66497a 100644
--- a/packages/desktop-client/src/components/reports/reports/Calendar.tsx
+++ b/packages/desktop-client/src/components/reports/reports/Calendar.tsx
@@ -122,7 +122,7 @@ function CalendarInner({ widget, parameters }: CalendarInnerProps) {
);
const { data: accounts = [] } = useAccounts();
- const payees = usePayees();
+ const { data: payees = [] } = usePayees();
const { data: { grouped: categoryGroups } = { grouped: [] } } =
useCategories();
diff --git a/packages/desktop-client/src/components/reports/reports/CustomReport.tsx b/packages/desktop-client/src/components/reports/reports/CustomReport.tsx
index ff7585c773..0555f31ddd 100644
--- a/packages/desktop-client/src/components/reports/reports/CustomReport.tsx
+++ b/packages/desktop-client/src/components/reports/reports/CustomReport.tsx
@@ -473,7 +473,7 @@ function CustomReportInner({ report: initialReport }: CustomReportInnerProps) {
const balanceTypeOp: balanceTypeOpType =
ReportOptions.balanceTypeMap.get(balanceType) || 'totalDebts';
const sortByOp: sortByOpType = sortBy || 'desc';
- const payees = usePayees();
+ const { data: payees = [] } = usePayees();
const { data: accounts = [] } = useAccounts();
const hasWarning = calculateHasWarning(conditions, {
diff --git a/packages/desktop-client/src/components/reports/reports/CustomReportListCards.tsx b/packages/desktop-client/src/components/reports/reports/CustomReportListCards.tsx
index e53d223d27..3e292717d3 100644
--- a/packages/desktop-client/src/components/reports/reports/CustomReportListCards.tsx
+++ b/packages/desktop-client/src/components/reports/reports/CustomReportListCards.tsx
@@ -80,7 +80,7 @@ function CustomReportListCardsInner({
const { menuItems: copyMenuItems, handleMenuSelect: handleCopyMenuSelect } =
useDashboardWidgetCopyMenu(onCopy);
- const payees = usePayees();
+ const { data: payees = [] } = usePayees();
const { data: accounts = [] } = useAccounts();
const { data: categories = { list: [], grouped: [] } } = useCategories();
diff --git a/packages/desktop-client/src/components/rules/RuleEditor.tsx b/packages/desktop-client/src/components/rules/RuleEditor.tsx
index 6e034e7752..7353cdfc42 100644
--- a/packages/desktop-client/src/components/rules/RuleEditor.tsx
+++ b/packages/desktop-client/src/components/rules/RuleEditor.tsx
@@ -64,7 +64,6 @@ import {
useSelected,
} from '@desktop-client/hooks/useSelected';
import { addNotification } from '@desktop-client/notifications/notificationsSlice';
-import { getPayees } from '@desktop-client/payees/payeesSlice';
import { aqlQuery } from '@desktop-client/queries/aqlQuery';
import { useDispatch } from '@desktop-client/redux';
import { disableUndo, enableUndo } from '@desktop-client/undo';
@@ -1023,8 +1022,6 @@ export function RuleEditor({
);
useEffect(() => {
- dispatch(getPayees());
-
// Disable undo while this modal is open
disableUndo();
return () => enableUndo();
diff --git a/packages/desktop-client/src/components/rules/ScheduleValue.tsx b/packages/desktop-client/src/components/rules/ScheduleValue.tsx
index fb2ab404e2..828c966cdb 100644
--- a/packages/desktop-client/src/components/rules/ScheduleValue.tsx
+++ b/packages/desktop-client/src/components/rules/ScheduleValue.tsx
@@ -10,9 +10,8 @@ import type { ScheduleEntity } from 'loot-core/types/models';
import { Value } from './Value';
-import { usePayees } from '@desktop-client/hooks/usePayees';
+import { usePayeesById } from '@desktop-client/hooks/usePayees';
import { useSchedules } from '@desktop-client/hooks/useSchedules';
-import { getPayeesById } from '@desktop-client/payees/payeesSlice';
type ScheduleValueProps = {
value: ScheduleEntity;
@@ -20,8 +19,7 @@ type ScheduleValueProps = {
export function ScheduleValue({ value }: ScheduleValueProps) {
const { t } = useTranslation();
- const payees = usePayees();
- const byId = getPayeesById(payees);
+ const { data: byId = {} } = usePayeesById();
const schedulesQuery = useMemo(() => q('schedules').select('*'), []);
const { schedules = [], isLoading } = useSchedules({ query: schedulesQuery });
diff --git a/packages/desktop-client/src/components/rules/Value.tsx b/packages/desktop-client/src/components/rules/Value.tsx
index fc09efd0d7..26f0f053ab 100644
--- a/packages/desktop-client/src/components/rules/Value.tsx
+++ b/packages/desktop-client/src/components/rules/Value.tsx
@@ -42,7 +42,7 @@ export function Value<T>({
const { t } = useTranslation();
const format = useFormat();
const dateFormat = useDateFormat() || 'MM/dd/yyyy';
- const payees = usePayees();
+ const { data: payees } = usePayees();
const {
data: { list: categories, grouped: categoryGroups } = {
list: [],
diff --git a/packages/desktop-client/src/components/schedules/ScheduleEditModal.tsx b/packages/desktop-client/src/components/schedules/ScheduleEditModal.tsx
index 3e67779894..65ba6428f1 100644
--- a/packages/desktop-client/src/components/schedules/ScheduleEditModal.tsx
+++ b/packages/desktop-client/src/components/schedules/ScheduleEditModal.tsx
@@ -18,12 +18,11 @@ import {
ModalCloseButton,
ModalHeader,
} from '@desktop-client/components/common/Modal';
-import { usePayees } from '@desktop-client/hooks/usePayees';
+import { usePayeesById } from '@desktop-client/hooks/usePayees';
import { useScheduleEdit } from '@desktop-client/hooks/useScheduleEdit';
import { useSelected } from '@desktop-client/hooks/useSelected';
import { pushModal } from '@desktop-client/modals/modalsSlice';
import type { Modal as ModalType } from '@desktop-client/modals/modalsSlice';
-import { getPayeesById } from '@desktop-client/payees/payeesSlice';
import { aqlQuery } from '@desktop-client/queries/aqlQuery';
import { useDispatch } from '@desktop-client/redux';
@@ -37,7 +36,7 @@ export function ScheduleEditModal({ id, transaction }: ScheduleEditModalProps) {
const adding = id == null;
const fromTrans = transaction != null;
- const payees = getPayeesById(usePayees());
+ const { data: payees } = usePayeesById();
const globalDispatch = useDispatch();
// Create initial schedule if adding from transaction
diff --git a/packages/desktop-client/src/components/schedules/SchedulesTable.tsx b/packages/desktop-client/src/components/schedules/SchedulesTable.tsx
index 4db49c1053..ebe33b3d28 100644
--- a/packages/desktop-client/src/components/schedules/SchedulesTable.tsx
+++ b/packages/desktop-client/src/components/schedules/SchedulesTable.tsx
@@ -339,7 +339,7 @@ export function SchedulesTable({
const dateFormat = useDateFormat() || 'MM/dd/yyyy';
const [showCompleted, setShowCompleted] = useState(false);
- const payees = usePayees();
+ const { data: payees } = usePayees();
const { data: accounts = [] } = useAccounts();
const filteredSchedules = useMemo(() => {
diff --git a/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx b/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx
index 0940a4c105..66d08d2549 100644
--- a/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx
+++ b/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx
@@ -33,7 +33,10 @@ import { SchedulesProvider } from '@desktop-client/hooks/useCachedSchedules';
import { SelectedProviderWithItems } from '@desktop-client/hooks/useSelected';
import { SplitsExpandedProvider } from '@desktop-client/hooks/useSplitsExpanded';
import { SpreadsheetProvider } from '@desktop-client/hooks/useSpreadsheet';
-import { TestProviders } from '@desktop-client/mocks';
+import { createTestQueryClient, TestProviders } from '@desktop-client/mocks';
+import { payeeQueries } from '@desktop-client/payees';
+
+const queryClient = createTestQueryClient();
vi.mock('loot-core/platform/client/connection');
vi.mock('../../hooks/useFeatureFlag', () => ({
@@ -68,22 +71,7 @@ const payees: PayeeEntity[] = [
name: 'This guy on the side of the road',
},
];
-vi.mock('../../hooks/usePayees', async importOriginal => {
- const actual =
- // oxlint-disable-next-line typescript/consistent-type-imports
- await importOriginal<typeof import('../../hooks/usePayees')>();
- return {
- ...actual,
- usePayees: () => payees,
- usePayeesById: () => {
- const payeesById: Record<string, PayeeEntity> = {};
- payees.forEach(payee => {
- payeesById[payee.id] = payee;
- });
- return payeesById;
- },
- };
-});
+queryClient.setQueryData(payeeQueries.list().queryKey, payees);
const categoryGroups = generateCategoryGroups([
{
@@ -195,7 +183,7 @@ function LiveTransactionTable(props: LiveTransactionTableProps) {
// implementation properly uses the right latest state even if the
// hook dependencies haven't changed
return (
- <TestProviders>
+ <TestProviders queryClient={queryClient}>
<AuthProvider>
<SpreadsheetProvider>
<SchedulesProvider>
diff --git a/packages/desktop-client/src/components/transactions/TransactionsTable.tsx b/packages/desktop-client/src/components/transactions/TransactionsTable.tsx
index 328c840f85..87dccf062e 100644
--- a/packages/desktop-client/src/components/transactions/TransactionsTable.tsx
+++ b/packages/desktop-client/src/components/transactions/TransactionsTable.tsx
@@ -138,7 +138,7 @@ import type { SplitsExpandedContextValue } from '@desktop-client/hooks/useSplits
import { pushModal } from '@desktop-client/modals/modalsSlice';
import { NotesTagFormatter } from '@desktop-client/notes/NotesTagFormatter';
import { addNotification } from '@desktop-client/notifications/notificationsSlice';
-import { getPayeesById } from '@desktop-client/payees/payeesSlice';
+import { getPayeesById } from '@desktop-client/payees';
import { useDispatch } from '@desktop-client/redux';
type TransactionHeaderProps = {
@@ -1028,6 +1028,7 @@ const Transaction = memo(function Transaction({
if (
name === 'account' &&
value &&
+ typeof value === 'string' &&
getAccountsById(accounts)[value].offbudget
) {
newTransaction.category = undefined;
diff --git a/packages/desktop-client/src/components/util/DisplayId.tsx b/packages/desktop-client/src/components/util/DisplayId.tsx
index ebca53d35f..a494fec983 100644
--- a/packages/desktop-client/src/components/util/DisplayId.tsx
+++ b/packages/desktop-client/src/components/util/DisplayId.tsx
@@ -42,7 +42,7 @@ function AccountDisplayId({ id, noneColor }) {
function PayeeDisplayId({ id, noneColor }) {
const { t } = useTranslation();
- const payee = usePayee(id);
+ const { data: payee } = usePayee(id);
return (
<TextOneLine
style={payee == null ? { color: noneColor } : null}
diff --git a/packages/desktop-client/src/global-events.ts b/packages/desktop-client/src/global-events.ts
index fcd24461b3..0e2ce4596c 100644
--- a/packages/desktop-client/src/global-events.ts
+++ b/packages/desktop-client/src/global-events.ts
@@ -13,7 +13,7 @@ import {
addGenericErrorNotification,
addNotification,
} from './notifications/notificationsSlice';
-import { reloadPayees } from './payees/payeesSlice';
+import { payeeQueries } from './payees';
import { loadPrefs } from './prefs/prefsSlice';
import type { AppStore } from './redux/store';
import * as syncEvents from './sync-events';
@@ -70,7 +70,9 @@ export function handleGlobalEvents(store: AppStore, queryClient: QueryClient) {
tables.includes('payees') ||
tables.includes('payee_mapping')
) {
- promises.push(store.dispatch(reloadPayees()));
+ queryClient.invalidateQueries({
+ queryKey: payeeQueries.lists(),
+ });
}
if (tables.includes('accounts')) {
diff --git a/packages/desktop-client/src/hooks/useAccountPreviewTransactions.ts b/packages/desktop-client/src/hooks/useAccountPreviewTransactions.ts
index 0424e9855d..cf8e0dd233 100644
--- a/packages/desktop-client/src/hooks/useAccountPreviewTransactions.ts
+++ b/packages/desktop-client/src/hooks/useAccountPreviewTransactions.ts
@@ -36,7 +36,7 @@ export function useAccountPreviewTransactions({
}: UseAccountPreviewTransactionsProps): UseAccountPreviewTransactionsResult {
const { data: accounts = [] } = useAccounts();
const accountsById = useMemo(() => groupById(accounts), [accounts]);
- const payees = usePayees();
+ const { data: payees = [] } = usePayees();
const payeesById = useMemo(() => groupById(payees), [payees]);
const getPayeeByTransferAccount = useCallback(
diff --git a/packages/desktop-client/src/hooks/useCommonPayees.ts b/packages/desktop-client/src/hooks/useCommonPayees.ts
new file mode 100644
index 0000000000..8148b4d1d8
--- /dev/null
+++ b/packages/desktop-client/src/hooks/useCommonPayees.ts
@@ -0,0 +1,7 @@
+import { useQuery } from '@tanstack/react-query';
+
+import { payeeQueries } from '@desktop-client/payees';
+
+export function useCommonPayees() {
+ return useQuery(payeeQueries.listCommon());
+}
diff --git a/packages/desktop-client/src/hooks/useDisplayPayee.tsx b/packages/desktop-client/src/hooks/useDisplayPayee.tsx
index 4008aa71ab..b738cf63e2 100644
--- a/packages/desktop-client/src/hooks/useDisplayPayee.tsx
+++ b/packages/desktop-client/src/hooks/useDisplayPayee.tsx
@@ -44,7 +44,7 @@ export function DisplayPayeeProvider({
});
const { data: accounts = [] } = useAccounts();
- const payeesById = usePayeesById();
+ const { data: payeesById = {} } = usePayeesById();
const displayPayees = useMemo(() => {
return transactions.reduce(
diff --git a/packages/desktop-client/src/hooks/useOrphanedPayees.ts b/packages/desktop-client/src/hooks/useOrphanedPayees.ts
new file mode 100644
index 0000000000..a65639ad9e
--- /dev/null
+++ b/packages/desktop-client/src/hooks/useOrphanedPayees.ts
@@ -0,0 +1,7 @@
+import { useQuery } from '@tanstack/react-query';
+
+import { payeeQueries } from '@desktop-client/payees/queries';
+
+export function useOrphanedPayees() {
+ return useQuery(payeeQueries.listOrphaned());
+}
diff --git a/packages/desktop-client/src/hooks/usePayee.ts b/packages/desktop-client/src/hooks/usePayee.ts
index 2606c60a87..12a92a3d0b 100644
--- a/packages/desktop-client/src/hooks/usePayee.ts
+++ b/packages/desktop-client/src/hooks/usePayee.ts
@@ -1,8 +1,11 @@
-import { useMemo } from 'react';
+import { useQuery } from '@tanstack/react-query';
-import { usePayees } from './usePayees';
+import { payeeQueries } from '@desktop-client/payees';
-export function usePayee(id: string) {
- const payees = usePayees();
- return useMemo(() => payees.find(p => p.id === id), [id, payees]);
+export function usePayee(id?: string | null) {
+ return useQuery({
+ ...payeeQueries.list(),
+ select: payees => payees.find(p => p.id === id),
+ enabled: !!id,
+ });
}
diff --git a/packages/desktop-client/src/hooks/usePayeeRuleCounts.ts b/packages/desktop-client/src/hooks/usePayeeRuleCounts.ts
index 349d4aaded..a278a128f9 100644
--- a/packages/desktop-client/src/hooks/usePayeeRuleCounts.ts
+++ b/packages/desktop-client/src/hooks/usePayeeRuleCounts.ts
@@ -1,33 +1,7 @@
-import { useCallback, useEffect, useState } from 'react';
+import { useQuery } from '@tanstack/react-query';
-import { send } from 'loot-core/platform/client/connection';
+import { payeeQueries } from '@desktop-client/payees';
-type PayeeRuleCounts = Map<string, number>;
-
-type UsePayeeRuleCountsResult = {
- ruleCounts: PayeeRuleCounts;
- isLoading: boolean;
- refetch: () => Promise<void>;
-};
-
-export function usePayeeRuleCounts(): UsePayeeRuleCountsResult {
- const [ruleCounts, setRuleCounts] = useState<PayeeRuleCounts>(new Map());
- const [isLoading, setIsLoading] = useState(true);
-
- const refetch = useCallback(async () => {
- setIsLoading(true);
- try {
- const counts = await send('payees-get-rule-counts');
- const countsMap = new Map(Object.entries(counts));
- setRuleCounts(countsMap);
- } finally {
- setIsLoading(false);
- }
- }, []);
-
- useEffect(() => {
- refetch();
- }, [refetch]);
-
- return { ruleCounts, isLoading, refetch };
+export function usePayeeRuleCounts() {
+ return useQuery(payeeQueries.ruleCounts());
}
diff --git a/packages/desktop-client/src/hooks/usePayees.ts b/packages/desktop-client/src/hooks/usePayees.ts
index 6d5e61e7f1..8ad5393ceb 100644
--- a/packages/desktop-client/src/hooks/usePayees.ts
+++ b/packages/desktop-client/src/hooks/usePayees.ts
@@ -1,45 +1,14 @@
-import { useEffect } from 'react';
+import { useQuery } from '@tanstack/react-query';
-import { useInitialMount } from './useInitialMount';
-
-import {
- getCommonPayees,
- getPayees,
- getPayeesById,
-} from '@desktop-client/payees/payeesSlice';
-import { useDispatch, useSelector } from '@desktop-client/redux';
-
-export function useCommonPayees() {
- const dispatch = useDispatch();
- const isInitialMount = useInitialMount();
- const isCommonPayeesDirty = useSelector(
- state => state.payees.isCommonPayeesDirty,
- );
-
- useEffect(() => {
- if (isInitialMount || isCommonPayeesDirty) {
- dispatch(getCommonPayees());
- }
- }, [dispatch, isInitialMount, isCommonPayeesDirty]);
-
- return useSelector(state => state.payees.commonPayees);
-}
+import { getPayeesById, payeeQueries } from '@desktop-client/payees';
export function usePayees() {
- const dispatch = useDispatch();
- const isInitialMount = useInitialMount();
- const isPayeesDirty = useSelector(state => state.payees.isPayeesDirty);
-
- useEffect(() => {
- if (isInitialMount || isPayeesDirty) {
- dispatch(getPayees());
- }
- }, [dispatch, isInitialMount, isPayeesDirty]);
-
- return useSelector(state => state.payees.payees);
+ return useQuery(payeeQueries.list());
}
export function usePayeesById() {
- const payees = usePayees();
- return getPayeesById(payees);
+ return useQuery({
+ ...payeeQueries.list(),
+ select: payees => getPayeesById(payees),
+ });
}
diff --git a/packages/desktop-client/src/index.tsx b/packages/desktop-client/src/index.tsx
index 3961f3a37b..6b1eb035c8 100644
--- a/packages/desktop-client/src/index.tsx
+++ b/packages/desktop-client/src/index.tsx
@@ -22,7 +22,6 @@ import { App } from './components/App';
import { ServerProvider } from './components/ServerContext';
import * as modalsSlice from './modals/modalsSlice';
import * as notificationsSlice from './notifications/notificationsSlice';
-import * as payeesSlice from './payees/payeesSlice';
import * as prefsSlice from './prefs/prefsSlice';
import { aqlQuery } from './queries/aqlQuery';
import { configureAppStore } from './redux/store';
@@ -42,7 +41,6 @@ const boundActions = bindActionCreators(
...budgetfilesSlice.actions,
...modalsSlice.actions,
...notificationsSlice.actions,
- ...payeesSlice.actions,
...prefsSlice.actions,
...transactionsSlice.actions,
...usersSlice.actions,
diff --git a/packages/desktop-client/src/mocks.tsx b/packages/desktop-client/src/mocks.tsx
index 9510e710ba..5df24c6c60 100644
--- a/packages/desktop-client/src/mocks.tsx
+++ b/packages/desktop-client/src/mocks.tsx
@@ -5,6 +5,7 @@ import { Provider } from 'react-redux';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { configureAppStore } from './redux/store';
+import type { AppStore } from './redux/store';
export function createTestQueryClient() {
return new QueryClient({
@@ -32,10 +33,24 @@ export function resetTestProviders() {
testStore = configureTestAppStore({ queryClient: testQueryClient });
}
-export function TestProviders({ children }: { children: ReactNode }) {
+export function createTestAppStore() {
+ return configureAppStore({
+ queryClient: testQueryClient,
+ });
+}
+
+export function TestProviders({
+ children,
+ queryClient,
+ store,
+}: {
+ queryClient?: QueryClient;
+ store?: AppStore;
+ children: ReactNode;
+}) {
return (
- <QueryClientProvider client={testQueryClient}>
- <Provider store={testStore}>{children}</Provider>
+ <QueryClientProvider client={queryClient ?? testQueryClient}>
+ <Provider store={store ?? testStore}>{children}</Provider>
</QueryClientProvider>
);
}
diff --git a/packages/desktop-client/src/payees/index.ts b/packages/desktop-client/src/payees/index.ts
new file mode 100644
index 0000000000..d0720956a0
--- /dev/null
+++ b/packages/desktop-client/src/payees/index.ts
@@ -0,0 +1,2 @@
+export * from './queries';
+export * from './mutations';
diff --git a/packages/desktop-client/src/payees/mutations.ts b/packages/desktop-client/src/payees/mutations.ts
new file mode 100644
index 0000000000..46a3d73b31
--- /dev/null
+++ b/packages/desktop-client/src/payees/mutations.ts
@@ -0,0 +1,65 @@
+import { useTranslation } from 'react-i18next';
+
+import { useMutation, useQueryClient } from '@tanstack/react-query';
+import type { QueryClient, QueryKey } from '@tanstack/react-query';
+import { v4 as uuidv4 } from 'uuid';
+
+import { send } from 'loot-core/platform/client/connection';
+import type { PayeeEntity } from 'loot-core/types/models';
+
+import { payeeQueries } from './queries';
+
+import { addNotification } from '@desktop-client/notifications/notificationsSlice';
+import { useDispatch } from '@desktop-client/redux';
+import type { AppDispatch } from '@desktop-client/redux/store';
+
+function invalidateQueries(queryClient: QueryClient, queryKey?: QueryKey) {
+ void queryClient.invalidateQueries({
+ queryKey: queryKey ?? payeeQueries.lists(),
+ });
+}
+
+function dispatchErrorNotification(
+ dispatch: AppDispatch,
+ message: string,
+ error?: Error,
+) {
+ dispatch(
+ addNotification({
+ notification: {
+ id: uuidv4(),
+ type: 'error',
+ message,
+ pre: error ? error.message : undefined,
+ },
+ }),
+ );
+}
+
+type CreatePayeePayload = {
+ name: PayeeEntity['name'];
+};
+
+export function useCreatePayeeMutation() {
+ const queryClient = useQueryClient();
+ const dispatch = useDispatch();
+ const { t } = useTranslation();
+
+ return useMutation({
+ mutationFn: async ({ name }: CreatePayeePayload) => {
+ const id: PayeeEntity['id'] = await send('payee-create', {
+ name: name.trim(),
+ });
+ return id;
+ },
+ onSuccess: () => invalidateQueries(queryClient),
+ onError: error => {
+ console.error('Error creating payee:', error);
+ dispatchErrorNotification(
+ dispatch,
+ t('There was an error creating the payee. Please try again.'),
+ error,
+ );
+ },
+ });
+}
diff --git a/packages/desktop-client/src/payees/payeesSlice.ts b/packages/desktop-client/src/payees/payeesSlice.ts
deleted file mode 100644
index 333630b9ad..0000000000
--- a/packages/desktop-client/src/payees/payeesSlice.ts
+++ /dev/null
@@ -1,230 +0,0 @@
-import { createSlice } from '@reduxjs/toolkit';
-import { t } from 'i18next';
-import memoizeOne from 'memoize-one';
-
-import { send } from 'loot-core/platform/client/connection';
-import { groupById } from 'loot-core/shared/util';
-import type { AccountEntity, PayeeEntity } from 'loot-core/types/models';
-
-import { getAccountsById } from '@desktop-client/accounts/accountsSlice';
-import { resetApp } from '@desktop-client/app/appSlice';
-import { createAppAsyncThunk } from '@desktop-client/redux';
-
-const sliceName = 'payees';
-
-type PayeesState = {
- commonPayees: PayeeEntity[];
- isCommonPayeesLoading: boolean;
- isCommonPayeesLoaded: boolean;
- isCommonPayeesDirty: boolean;
- payees: PayeeEntity[];
- isPayeesLoading: boolean;
- isPayeesLoaded: boolean;
- isPayeesDirty: boolean;
-};
-
-const initialState: PayeesState = {
- commonPayees: [],
- isCommonPayeesLoading: false,
- isCommonPayeesLoaded: false,
- isCommonPayeesDirty: false,
- payees: [],
- isPayeesLoading: false,
- isPayeesLoaded: false,
- isPayeesDirty: false,
-};
-
-const payeesSlice = createSlice({
- name: sliceName,
- initialState,
- reducers: {
- markPayeesDirty(state) {
- _markPayeesDirty(state);
- },
- },
- extraReducers: builder => {
- builder.addCase(resetApp, () => initialState);
-
- builder.addCase(createPayee.fulfilled, _markPayeesDirty);
-
- builder.addCase(reloadCommonPayees.fulfilled, (state, action) => {
- _loadCommonPayees(state, action.payload);
- });
-
- builder.addCase(reloadCommonPayees.rejected, state => {
- state.isCommonPayeesLoading = false;
- });
-
- builder.addCase(reloadCommonPayees.pending, state => {
- state.isCommonPayeesLoading = true;
- });
-
- builder.addCase(getCommonPayees.fulfilled, (state, action) => {
- _loadCommonPayees(state, action.payload);
- });
-
- builder.addCase(getCommonPayees.rejected, state => {
- state.isCommonPayeesLoading = false;
- });
-
- builder.addCase(getCommonPayees.pending, state => {
- state.isCommonPayeesLoading = true;
- });
-
- builder.addCase(reloadPayees.fulfilled, (state, action) => {
- _loadPayees(state, action.payload);
- });
-
- builder.addCase(reloadPayees.rejected, state => {
- state.isPayeesLoading = false;
- });
-
- builder.addCase(reloadPayees.pending, state => {
- state.isPayeesLoading = true;
- });
-
- builder.addCase(getPayees.fulfilled, (state, action) => {
- _loadPayees(state, action.payload);
- });
-
- builder.addCase(getPayees.rejected, state => {
- state.isPayeesLoading = false;
- });
-
- builder.addCase(getPayees.pending, state => {
- state.isPayeesLoading = true;
- });
- },
-});
-
-type CreatePayeePayload = {
- name: PayeeEntity['name'];
-};
-
-function translatePayees(
- payees: PayeeEntity[] | null | undefined,
-): PayeeEntity[] | null | undefined {
- return (
- payees?.map(payee =>
- payee.name === 'Starting Balance'
- ? { ...payee, name: t('Starting Balance') }
- : payee,
- ) ?? payees
- );
-}
-
-export const createPayee = createAppAsyncThunk(
- `${sliceName}/createPayee`,
- async ({ name }: CreatePayeePayload) => {
- const id: PayeeEntity['id'] = await send('payee-create', {
- name: name.trim(),
- });
- return id;
- },
-);
-
-export const getCommonPayees = createAppAsyncThunk(
- `${sliceName}/getCommonPayees`,
- async () => {
- const payees: PayeeEntity[] = await send('common-payees-get');
- return translatePayees(payees) as PayeeEntity[];
- },
- {
- condition: (_, { getState }) => {
- const { payees } = getState();
- return (
- !payees.isCommonPayeesLoading &&
- (payees.isCommonPayeesDirty || !payees.isCommonPayeesLoaded)
- );
- },
- },
-);
-
-export const reloadCommonPayees = createAppAsyncThunk(
- `${sliceName}/reloadCommonPayees`,
- async () => {
- const payees: PayeeEntity[] = await send('common-payees-get');
- return translatePayees(payees) as PayeeEntity[];
- },
-);
-
-export const getPayees = createAppAsyncThunk(
- `${sliceName}/getPayees`,
- async () => {
- const payees: PayeeEntity[] = await send('payees-get');
- return translatePayees(payees) as PayeeEntity[];
- },
- {
- condition: (_, { getState }) => {
- const { payees } = getState();
- return (
- !payees.isPayeesLoading &&
- (payees.isPayeesDirty || !payees.isPayeesLoaded)
- );
- },
- },
-);
-
-export const reloadPayees = createAppAsyncThunk(
- `${sliceName}/reloadPayees`,
- async () => {
- const payees: PayeeEntity[] = await send('payees-get');
- return translatePayees(payees) as PayeeEntity[];
- },
-);
-
-export const getActivePayees = memoizeOne(
- (payees: PayeeEntity[], accounts: AccountEntity[]) => {
- const accountsById = getAccountsById(accounts);
-
- return translatePayees(
- payees.filter(payee => {
- if (payee.transfer_acct) {
- const account = accountsById[payee.transfer_acct];
- return account != null && !account.closed;
- }
- return true;
- }) as PayeeEntity[],
- );
- },
-);
-
-export const getPayeesById = memoizeOne(
- (payees: PayeeEntity[] | null | undefined) =>
- groupById(translatePayees(payees)),
-);
-
-export const { name, reducer, getInitialState } = payeesSlice;
-
-export const actions = {
- ...payeesSlice.actions,
- createPayee,
- getCommonPayees,
- reloadCommonPayees,
- getPayees,
- reloadPayees,
-};
-
-export const { markPayeesDirty } = payeesSlice.actions;
-
-function _loadCommonPayees(
- state: PayeesState,
- commonPayees: PayeesState['commonPayees'],
-) {
- state.commonPayees = translatePayees(commonPayees) as PayeeEntity[];
- state.isCommonPayeesLoading = false;
- state.isCommonPayeesLoaded = true;
- state.isCommonPayeesDirty = false;
-}
-
-function _loadPayees(state: PayeesState, payees: PayeesState['payees']) {
- state.payees = translatePayees(payees) as PayeeEntity[];
- state.isPayeesLoading = false;
- state.isPayeesLoaded = true;
- state.isPayeesDirty = false;
-}
-
-function _markPayeesDirty(state: PayeesState) {
- state.isCommonPayeesDirty = true;
- state.isPayeesDirty = true;
-}
diff --git a/packages/desktop-client/src/payees/queries.ts b/packages/desktop-client/src/payees/queries.ts
new file mode 100644
index 0000000000..3b4c497c9e
--- /dev/null
+++ b/packages/desktop-client/src/payees/queries.ts
@@ -0,0 +1,86 @@
+import { queryOptions } from '@tanstack/react-query';
+import { t } from 'i18next';
+import memoizeOne from 'memoize-one';
+
+import { send } from 'loot-core/platform/client/connection';
+import { groupById } from 'loot-core/shared/util';
+import type { AccountEntity, PayeeEntity } from 'loot-core/types/models';
+
+import { getAccountsById } from '@desktop-client/accounts/accountsSlice';
+
+export const payeeQueries = {
+ all: () => ['payees'],
+ lists: () => [...payeeQueries.all(), 'lists'],
+ list: () =>
+ queryOptions<PayeeEntity[]>({
+ queryKey: [...payeeQueries.lists()],
+ queryFn: async () => {
+ const payees: PayeeEntity[] = (await send('payees-get')) ?? [];
+ return translatePayees(payees);
+ },
+ placeholderData: [],
+ // Manually invalidated when payees change via sync events
+ staleTime: Infinity,
+ }),
+ listCommon: () =>
+ queryOptions<PayeeEntity[]>({
+ queryKey: [...payeeQueries.lists(), 'common'],
+ queryFn: async () => {
+ const payees: PayeeEntity[] = (await send('common-payees-get')) ?? [];
+ return translatePayees(payees);
+ },
+ placeholderData: [],
+ // Manually invalidated when payees change via sync events
+ staleTime: Infinity,
+ }),
+ listOrphaned: () =>
+ queryOptions<Pick<PayeeEntity, 'id'>[]>({
+ queryKey: [...payeeQueries.lists(), 'orphaned'],
+ queryFn: async () => {
+ const payees: Pick<PayeeEntity, 'id'>[] =
+ (await send('payees-get-orphaned')) ?? [];
+ return payees;
+ },
+ placeholderData: [],
+ // Manually invalidated when payees change via sync events
+ staleTime: Infinity,
+ }),
+ ruleCounts: () =>
+ queryOptions<Map<PayeeEntity['id'], number>>({
+ queryKey: [...payeeQueries.lists(), 'ruleCounts'],
+ queryFn: async () => {
+ const counts = await send('payees-get-rule-counts');
+ return new Map(Object.entries(counts ?? {}));
+ },
+ placeholderData: new Map(),
+ }),
+};
+
+export const getActivePayees = memoizeOne(
+ (payees: PayeeEntity[], accounts: AccountEntity[]) => {
+ const accountsById = getAccountsById(accounts);
+
+ return translatePayees(
+ payees.filter(payee => {
+ if (payee.transfer_acct) {
+ const account = accountsById[payee.transfer_acct];
+ return account != null && !account.closed;
+ }
+ return true;
+ }),
+ );
+ },
+);
+
+export const getPayeesById = memoizeOne(
+ (payees: PayeeEntity[] | null | undefined) =>
+ groupById(translatePayees(payees || [])),
+);
+
+function translatePayees(payees: PayeeEntity[]): PayeeEntity[] {
+ return payees.map(payee =>
+ payee.name === 'Starting Balance'
+ ? { ...payee, name: t('Starting Balance') }
+ : payee,
+ );
+}
diff --git a/packages/desktop-client/src/redux/store.ts b/packages/desktop-client/src/redux/store.ts
index 170a8df092..fd601d8c3d 100644
--- a/packages/desktop-client/src/redux/store.ts
+++ b/packages/desktop-client/src/redux/store.ts
@@ -27,10 +27,6 @@ import {
name as notificationsSliceName,
reducer as notificationsSliceReducer,
} from '@desktop-client/notifications/notificationsSlice';
-import {
- name as payeesSliceName,
- reducer as payeesSliceReducer,
-} from '@desktop-client/payees/payeesSlice';
import {
name as prefsSliceName,
reducer as prefsSliceReducer,
@@ -50,7 +46,6 @@ const rootReducer = combineReducers({
[budgetfilesSliceName]: budgetfilesSliceReducer,
[modalsSliceName]: modalsSliceReducer,
[notificationsSliceName]: notificationsSliceReducer,
- [payeesSliceName]: payeesSliceReducer,
[prefsSliceName]: prefsSliceReducer,
[transactionsSliceName]: transactionsSliceReducer,
[usersSliceName]: usersSliceReducer,
diff --git a/packages/desktop-client/src/sync-events.ts b/packages/desktop-client/src/sync-events.ts
index d2ccb3d549..392a6c8e1e 100644
--- a/packages/desktop-client/src/sync-events.ts
+++ b/packages/desktop-client/src/sync-events.ts
@@ -13,7 +13,7 @@ import {
import { pushModal } from './modals/modalsSlice';
import { addNotification } from './notifications/notificationsSlice';
import type { Notification } from './notifications/notificationsSlice';
-import { reloadPayees } from './payees/payeesSlice';
+import { payeeQueries } from './payees';
import { loadPrefs } from './prefs/prefsSlice';
import type { AppStore } from './redux/store';
import { signOut } from './users/usersSlice';
@@ -81,7 +81,9 @@ export function listenForSyncEvent(store: AppStore, queryClient: QueryClient) {
tables.includes('payees') ||
tables.includes('payee_mapping')
) {
- store.dispatch(reloadPayees());
+ queryClient.invalidateQueries({
+ queryKey: payeeQueries.lists(),
+ });
}
if (tables.includes('accounts')) {
diff --git a/packages/loot-core/src/mocks/index.ts b/packages/loot-core/src/mocks/index.ts
index 051af3872f..c9a093bec0 100644
--- a/packages/loot-core/src/mocks/index.ts
+++ b/packages/loot-core/src/mocks/index.ts
@@ -2,7 +2,6 @@ import { v4 as uuidv4 } from 'uuid';
import * as monthUtils from '../shared/months';
import type {
- _SyncFields,
AccountEntity,
CategoryEntity,
CategoryGroupEntity,
@@ -47,7 +46,20 @@ export function generateAccount(
return offlineAccount;
}
-function emptySyncFields(): _SyncFields<false> {
+function emptySyncFields(): Pick<
+ AccountEntity,
+ | 'account_id'
+ | 'bank'
+ | 'bankId'
+ | 'bankName'
+ | 'mask'
+ | 'official_name'
+ | 'balance_current'
+ | 'balance_available'
+ | 'balance_limit'
+ | 'account_sync_source'
+ | 'last_sync'
+> {
return {
account_id: null,
bank: null,
diff --git a/packages/loot-core/src/server/accounts/app.ts b/packages/loot-core/src/server/accounts/app.ts
index ac7aeb993c..13462677f0 100644
--- a/packages/loot-core/src/server/accounts/app.ts
+++ b/packages/loot-core/src/server/accounts/app.ts
@@ -112,7 +112,7 @@ async function getAccounts(): Promise<AccountEntity[]> {
balance_limit: dbAccount.balance_limit ?? null,
account_sync_source: dbAccount.account_sync_source ?? null,
last_sync: dbAccount.last_sync ?? null,
- }) as AccountEntity,
+ }) satisfies AccountEntity,
);
}
diff --git a/packages/loot-core/src/types/models/account.ts b/packages/loot-core/src/types/models/account.ts
index 018f16ea95..08c9f44a3a 100644
--- a/packages/loot-core/src/types/models/account.ts
+++ b/packages/loot-core/src/types/models/account.ts
@@ -6,20 +6,19 @@ export type AccountEntity = {
sort_order: number;
last_reconciled: string | null;
tombstone: 0 | 1;
-} & (_SyncFields<true> | _SyncFields<false>);
-export type _SyncFields<T> = {
- account_id: T extends true ? string : null;
- bank: T extends true ? string : null;
- bankName: T extends true ? string : null;
- bankId: T extends true ? string : null;
- mask: T extends true ? string : null; // end of bank account number
- official_name: T extends true ? string : null;
- balance_current: T extends true ? number : null;
- balance_available: T extends true ? number : null;
- balance_limit: T extends true ? number : null;
- account_sync_source: T extends true ? AccountSyncSource : null;
- last_sync: T extends true ? string : null;
+ // Sync fields
+ account_id: string | null;
+ bank: string | null;
+ bankName: string | null;
+ bankId: string | null;
+ mask: string | null; // end of bank account number
+ official_name: string | null;
+ balance_current: number | null;
+ balance_available: number | null;
+ balance_limit: number | null;
+ account_sync_source: AccountSyncSource | null;
+ last_sync: string | null;
};
export type AccountSyncSource = 'simpleFin' | 'goCardless' | 'pluggyai';
diff --git a/tsconfig.json b/tsconfig.json
index 186558c2c1..581705df21 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -56,7 +56,8 @@
"**/lib-dist/*",
"**/test-results/*",
"**/playwright-report/*",
- "**/service-worker/*"
+ "**/service-worker/*",
+ "packages/docs/**/*"
],
"ts-node": {
"compilerOptions": {
diff --git a/upcoming-release-notes/6880.md b/upcoming-release-notes/6880.md
new file mode 100644
index 0000000000..95128dda9c
--- /dev/null
+++ b/upcoming-release-notes/6880.md
@@ -0,0 +1,6 @@
+---
+category: Enhancements
+authors: [joel-jeremy]
+---
+
+Migrate payee and account state management from Redux to React Query for improved performance.