Skip to content

A local-first personal finance app

Update global event listeners to handle sync server and DB update sync events (#4161)

Joel Jeremy Marquezf0c81eebbf48
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 0cdf97f16d..0108f12b42 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -662,6 +662,12 @@ export default [
message:
"Please import Actual's useSelector() hook from `src/redux` instead.",
},
+ {
+ name: 'react-redux',
+ importNames: ['useStore'],
+ message:
+ "Please import Actual's useStore() hook from `src/redux` instead.",
+ },
],
},
],
diff --git a/packages/desktop-client/src/components/App.tsx b/packages/desktop-client/src/components/App.tsx
index 74000f5d37..675d01b9f8 100644
--- a/packages/desktop-client/src/components/App.tsx
+++ b/packages/desktop-client/src/components/App.tsx
@@ -26,9 +26,10 @@ import {
send,
} from 'loot-core/src/platform/client/fetch';
+import { handleGlobalEvents } from '../global-events';
import { useMetadataPref } from '../hooks/useMetadataPref';
import { installPolyfills } from '../polyfills';
-import { useDispatch, useSelector } from '../redux';
+import { useDispatch, useSelector, useStore } from '../redux';
import { styles, hasHiddenScrollbars, ThemeStyle, useTheme } from '../style';
import { ExposeNavigate } from '../util/router-tools';
@@ -160,6 +161,10 @@ function ErrorFallback({ error }: FallbackProps) {
}
export function App() {
+ const store = useStore();
+
+ useEffect(() => handleGlobalEvents(store), [store]);
+
const [hiddenScrollbars, setHiddenScrollbars] = useState(
hasHiddenScrollbars(),
);
diff --git a/packages/desktop-client/src/components/budget/index.tsx b/packages/desktop-client/src/components/budget/index.tsx
index 1c29d819eb..f61a9aa86a 100644
--- a/packages/desktop-client/src/components/budget/index.tsx
+++ b/packages/desktop-client/src/components/budget/index.tsx
@@ -16,7 +16,7 @@ import {
} from 'loot-core/client/queries/queriesSlice';
import { addNotification, pushModal } from 'loot-core/src/client/actions';
import { useSpreadsheet } from 'loot-core/src/client/SpreadsheetProvider';
-import { send, listen } from 'loot-core/src/platform/client/fetch';
+import { send } from 'loot-core/src/platform/client/fetch';
import * as monthUtils from 'loot-core/src/shared/months';
import { useCategories } from '../../hooks/useCategories';
@@ -83,13 +83,9 @@ function BudgetInner(props: BudgetInnerProps) {
const [initialized, setInitialized] = useState(false);
const { grouped: categoryGroups } = useCategories();
- function loadCategories() {
- dispatch(getCategories());
- }
-
useEffect(() => {
async function run() {
- loadCategories();
+ await dispatch(getCategories());
const { start, end } = await send('get-budget-bounds');
setBounds({ start, end });
@@ -105,31 +101,6 @@ function BudgetInner(props: BudgetInnerProps) {
}
run();
-
- const unlistens = [
- listen('sync-event', event => {
- if (event.type === 'success') {
- const tables = event.tables;
- if (
- tables.includes('categories') ||
- tables.includes('category_mapping') ||
- tables.includes('category_groups')
- ) {
- loadCategories();
- }
- }
- }),
-
- listen('undo-event', ({ tables }) => {
- if (tables.includes('categories')) {
- loadCategories();
- }
- }),
- ];
-
- return () => {
- unlistens.forEach(unlisten => unlisten());
- };
}, []);
useEffect(() => {
diff --git a/packages/desktop-client/src/components/mobile/accounts/AccountTransactions.tsx b/packages/desktop-client/src/components/mobile/accounts/AccountTransactions.tsx
index 87e1051761..33493d2ae1 100644
--- a/packages/desktop-client/src/components/mobile/accounts/AccountTransactions.tsx
+++ b/packages/desktop-client/src/components/mobile/accounts/AccountTransactions.tsx
@@ -22,7 +22,6 @@ import {
} from 'loot-core/client/data-hooks/transactions';
import * as queries from 'loot-core/client/queries';
import {
- getPayees,
markAccountRead,
reopenAccount,
updateAccount,
@@ -279,10 +278,6 @@ function TransactionListWithPreviews({
) {
reloadTransactions();
}
-
- if (tables.includes('payees') || tables.includes('payee_mapping')) {
- dispatch(getPayees());
- }
}
});
}, [dispatch, reloadTransactions]);
diff --git a/packages/desktop-client/src/components/mobile/budget/CategoryTransactions.tsx b/packages/desktop-client/src/components/mobile/budget/CategoryTransactions.tsx
index 66c56dc9df..d196d053d1 100644
--- a/packages/desktop-client/src/components/mobile/budget/CategoryTransactions.tsx
+++ b/packages/desktop-client/src/components/mobile/budget/CategoryTransactions.tsx
@@ -5,7 +5,6 @@ import {
useTransactionsSearch,
} from 'loot-core/client/data-hooks/transactions';
import * as queries from 'loot-core/client/queries';
-import { getPayees } from 'loot-core/client/queries/queriesSlice';
import { listen } from 'loot-core/platform/client/fetch';
import * as monthUtils from 'loot-core/shared/months';
import { q } from 'loot-core/shared/query';
@@ -72,10 +71,6 @@ export function CategoryTransactions({
) {
reloadTransactions();
}
-
- if (tables.includes('payees') || tables.includes('payee_mapping')) {
- dispatch(getPayees());
- }
}
});
}, [dispatch, reloadTransactions]);
diff --git a/packages/desktop-client/src/components/mobile/budget/index.tsx b/packages/desktop-client/src/components/mobile/budget/index.tsx
index 86d96330f6..6ae7cb2f35 100644
--- a/packages/desktop-client/src/components/mobile/budget/index.tsx
+++ b/packages/desktop-client/src/components/mobile/budget/index.tsx
@@ -9,14 +9,13 @@ import {
createGroup,
deleteCategory,
deleteGroup,
- getCategories,
moveCategory,
moveCategoryGroup,
updateCategory,
updateGroup,
} from 'loot-core/client/queries/queriesSlice';
import { useSpreadsheet } from 'loot-core/src/client/SpreadsheetProvider';
-import { send, listen } from 'loot-core/src/platform/client/fetch';
+import { send } from 'loot-core/src/platform/client/fetch';
import * as monthUtils from 'loot-core/src/shared/months';
import { useCategories } from '../../../hooks/useCategories';
@@ -67,22 +66,6 @@ export function Budget() {
}
init();
-
- const unlisten = listen('sync-event', event => {
- if (event.type === 'success') {
- const tables = event.tables;
- if (
- tables.includes('categories') ||
- tables.includes('category_mapping') ||
- tables.includes('category_groups')
- ) {
- // TODO: is this loading every time?
- dispatch(getCategories());
- }
- }
- });
-
- return () => unlisten();
}, [budgetType, startMonth, dispatch, spreadsheet]);
const onBudgetAction = useCallback(
diff --git a/packages/desktop-client/src/components/payees/ManagePayeesWithData.tsx b/packages/desktop-client/src/components/payees/ManagePayeesWithData.tsx
index 1894382f80..faf52e9361 100644
--- a/packages/desktop-client/src/components/payees/ManagePayeesWithData.tsx
+++ b/packages/desktop-client/src/components/payees/ManagePayeesWithData.tsx
@@ -67,7 +67,6 @@ export function ManagePayeesWithData({
return;
}
- await dispatch(getPayees());
await refetchOrphanedPayees();
const targetId =
diff --git a/packages/desktop-client/src/global-events.ts b/packages/desktop-client/src/global-events.ts
index ed8d7b3311..cb1c6e2a1e 100644
--- a/packages/desktop-client/src/global-events.ts
+++ b/packages/desktop-client/src/global-events.ts
@@ -20,58 +20,30 @@ import { listen } from 'loot-core/src/platform/client/fetch';
import * as undo from 'loot-core/src/platform/client/undo';
export function handleGlobalEvents(store: AppStore) {
- listen('server-error', () => {
+ const unlistenServerError = listen('server-error', () => {
store.dispatch(addGenericErrorNotification());
});
- listen('orphaned-payees', ({ orphanedIds, updatedPayeeIds }) => {
- // Right now, it prompts to merge into the first payee
- store.dispatch(
- pushModal('merge-unused-payees', {
- payeeIds: orphanedIds,
- targetPayeeId: updatedPayeeIds[0],
- }),
- );
- });
-
- listen('schedules-offline', () => {
- store.dispatch(pushModal('schedule-posts-offline-notification'));
- });
-
- // This is experimental: we sync data locally automatically when
- // data changes from the backend
- listen('sync-event', async event => {
- // We don't need to query anything until the file is loaded, and
- // sync events might come in if the file is being synced before
- // being loaded (happens when downloading)
- const prefs = store.getState().prefs.local;
- if (prefs && prefs.id) {
- if (event.type === 'applied') {
- const tables = event.tables;
- if (tables.includes('payees') || tables.includes('payee_mapping')) {
- store.dispatch(getPayees());
- }
- }
- }
- });
-
- // TODO: Should this run on mobile too?
- listen('sync-event', async ({ type }) => {
- if (type === 'unauthorized') {
+ const unlistenOrphanedPayees = listen(
+ 'orphaned-payees',
+ ({ orphanedIds, updatedPayeeIds }) => {
+ // Right now, it prompts to merge into the first payee
store.dispatch(
- addNotification({
- type: 'warning',
- message: 'Unable to authenticate with server',
- sticky: true,
- id: 'auth-issue',
+ pushModal('merge-unused-payees', {
+ payeeIds: orphanedIds,
+ targetPayeeId: updatedPayeeIds[0],
}),
);
- }
+ },
+ );
+
+ const unlistenSchedulesOffline = listen('schedules-offline', () => {
+ store.dispatch(pushModal('schedule-posts-offline-notification'));
});
- sharedListeners.listenForSyncEvent(store);
+ const unlistenSync = sharedListeners.listenForSyncEvent(store);
- listen('undo-event', undoState => {
+ const unlistenUndo = listen('undo-event', undoState => {
const { tables, undoTag } = undoState;
const promises: Promise<unknown>[] = [];
@@ -83,6 +55,14 @@ export function handleGlobalEvents(store: AppStore) {
promises.push(store.dispatch(getCategories()));
}
+ if (
+ tables.includes('accounts') ||
+ tables.includes('payees') ||
+ tables.includes('payee_mapping')
+ ) {
+ promises.push(store.dispatch(getPayees()));
+ }
+
if (tables.includes('accounts')) {
promises.push(store.dispatch(getAccounts()));
}
@@ -121,7 +101,7 @@ export function handleGlobalEvents(store: AppStore) {
}
});
- listen('fallback-write-error', () => {
+ const unlistenFallbackWriteError = listen('fallback-write-error', () => {
store.dispatch(
addNotification({
type: 'error',
@@ -135,33 +115,48 @@ export function handleGlobalEvents(store: AppStore) {
);
});
- listen('start-load', () => {
+ const unlistenStartLoad = listen('start-load', () => {
store.dispatch(closeBudgetUI());
store.dispatch(setAppState({ loadingText: '' }));
});
- listen('finish-load', () => {
+ const unlistenFinishLoad = listen('finish-load', () => {
store.dispatch(closeModal());
store.dispatch(setAppState({ loadingText: null }));
store.dispatch(loadPrefs());
});
- listen('start-import', () => {
+ const unlistenStartImport = listen('start-import', () => {
store.dispatch(closeBudgetUI());
});
- listen('finish-import', () => {
+ const unlistenFinishImport = listen('finish-import', () => {
store.dispatch(closeModal());
store.dispatch(setAppState({ loadingText: null }));
store.dispatch(loadPrefs());
});
- listen('show-budgets', () => {
+ const unlistenShowBudgets = listen('show-budgets', () => {
store.dispatch(closeBudgetUI());
store.dispatch(setAppState({ loadingText: null }));
});
- listen('api-fetch-redirected', () => {
+ const unlistenApiFetchRedirected = listen('api-fetch-redirected', () => {
window.Actual.reload();
});
+
+ return () => {
+ unlistenServerError();
+ unlistenOrphanedPayees();
+ unlistenSchedulesOffline();
+ unlistenSync();
+ unlistenUndo();
+ unlistenFallbackWriteError();
+ unlistenStartLoad();
+ unlistenFinishLoad();
+ unlistenStartImport();
+ unlistenFinishImport();
+ unlistenShowBudgets();
+ unlistenApiFetchRedirected();
+ };
}
diff --git a/packages/desktop-client/src/index.tsx b/packages/desktop-client/src/index.tsx
index 0ebe143d9c..7fdacf04a7 100644
--- a/packages/desktop-client/src/index.tsx
+++ b/packages/desktop-client/src/index.tsx
@@ -26,7 +26,6 @@ import { q } from 'loot-core/src/shared/query';
import { AuthProvider } from './auth/AuthProvider';
import { App } from './components/App';
import { ServerProvider } from './components/ServerContext';
-import { handleGlobalEvents } from './global-events';
// See https://github.com/WICG/focus-visible. Only makes the blue
// focus outline appear from keyboard events.
@@ -42,9 +41,6 @@ const boundActions = bindActionCreators(
store.dispatch,
);
-// Listen for global events from the server or main process
-handleGlobalEvents(store);
-
async function appFocused() {
await send('app-focused');
}
diff --git a/packages/desktop-client/src/redux/index.ts b/packages/desktop-client/src/redux/index.ts
index 5cb89bbd39..077a41e94b 100644
--- a/packages/desktop-client/src/redux/index.ts
+++ b/packages/desktop-client/src/redux/index.ts
@@ -1,9 +1,15 @@
import {
useDispatch as useReduxDispatch,
useSelector as useReduxSelector,
+ useStore as useReduxStore,
} from 'react-redux';
-import { type AppDispatch, type RootState } from 'loot-core/client/store';
+import {
+ type AppStore,
+ type AppDispatch,
+ type RootState,
+} from 'loot-core/client/store';
+export const useStore = useReduxStore.withTypes<AppStore>();
export const useDispatch = useReduxDispatch.withTypes<AppDispatch>();
export const useSelector = useReduxSelector.withTypes<RootState>();
diff --git a/packages/loot-core/src/client/shared-listeners.ts b/packages/loot-core/src/client/shared-listeners.ts
index 38f38aa439..bad952eb56 100644
--- a/packages/loot-core/src/client/shared-listeners.ts
+++ b/packages/loot-core/src/client/shared-listeners.ts
@@ -17,16 +17,30 @@ import type { Notification } from './state-types/notifications';
import { type AppStore } from './store';
export function listenForSyncEvent(store: AppStore) {
+ // TODO: Should this run on mobile too?
+ const unlistenUnauthorized = listen('sync-event', async ({ type }) => {
+ if (type === 'unauthorized') {
+ store.dispatch(
+ addNotification({
+ type: 'warning',
+ message: 'Unable to authenticate with server',
+ sticky: true,
+ id: 'auth-issue',
+ }),
+ );
+ }
+ });
+
let attemptedSyncRepair = false;
- listen('sync-event', event => {
+ const unlistenSuccess = listen('sync-event', event => {
const prefs = store.getState().prefs.local;
if (!prefs || !prefs.id) {
// Do nothing if no budget is loaded
return;
}
- if (event.type === 'success') {
+ if (event.type === 'success' || event.type === 'applied') {
if (attemptedSyncRepair) {
attemptedSyncRepair = false;
@@ -53,7 +67,12 @@ export function listenForSyncEvent(store: AppStore) {
store.dispatch(getCategories());
}
- if (tables.includes('payees') || tables.includes('payee_mapping')) {
+ if (
+ // Sync on accounts change because so that transfer payees are updated
+ tables.includes('accounts') ||
+ tables.includes('payees') ||
+ tables.includes('payee_mapping')
+ ) {
store.dispatch(getPayees());
}
@@ -324,4 +343,9 @@ export function listenForSyncEvent(store: AppStore) {
}
}
});
+
+ return () => {
+ unlistenUnauthorized();
+ unlistenSuccess();
+ };
}
diff --git a/upcoming-release-notes/4161.md b/upcoming-release-notes/4161.md
new file mode 100644
index 0000000000..ce6eb231ec
--- /dev/null
+++ b/upcoming-release-notes/4161.md
@@ -0,0 +1,6 @@
+---
+category: Bugfix
+authors: [joel-jeremy]
+---
+
+Fix payees autocomplete not reflecting new name of a renamed account (under the Transfer To/From section)