A local-first personal finance app
Prevent unnecessary calls to DB if same redux action is already pending (#5579)
Joel Jeremy Marquez91a8bc3ef188
diff --git a/packages/desktop-client/src/accounts/accountsSlice.ts b/packages/desktop-client/src/accounts/accountsSlice.tsindex 1ddc2bb995..ceed6a6f26 100644--- a/packages/desktop-client/src/accounts/accountsSlice.ts+++ b/packages/desktop-client/src/accounts/accountsSlice.ts@@ -13,8 +13,8 @@ import {import { resetApp } from '@desktop-client/app/appSlice';import { addNotification } from '@desktop-client/notifications/notificationsSlice';import {- getAccounts,- getPayees,+ markAccountsDirty,+ markPayeesDirty,setNewTransactions,} from '@desktop-client/queries/queriesSlice';import { createAppAsyncThunk } from '@desktop-client/redux';@@ -86,7 +86,7 @@ export const unlinkAccount = createAppAsyncThunk(const { markAccountSuccess } = accountsSlice.actions;await send('account-unlink', { id });dispatch(markAccountSuccess({ id }));- dispatch(getAccounts());+ dispatch(markAccountsDirty());},);@@ -109,8 +109,8 @@ export const linkAccount = createAppAsyncThunk(upgradingId,offBudget,});- dispatch(getPayees());- dispatch(getAccounts());+ dispatch(markPayeesDirty());+ dispatch(markAccountsDirty());},);@@ -131,8 +131,8 @@ export const linkAccountSimpleFin = createAppAsyncThunk(upgradingId,offBudget,});- dispatch(getPayees());- dispatch(getAccounts());+ dispatch(markPayeesDirty());+ dispatch(markAccountsDirty());},);@@ -153,8 +153,8 @@ export const linkAccountPluggyAi = createAppAsyncThunk(upgradingId,offBudget,});- dispatch(getPayees());- dispatch(getAccounts());+ dispatch(markPayeesDirty());+ dispatch(markAccountsDirty());},);@@ -215,7 +215,7 @@ function handleSyncResponse(resMatchedTransactions.push(...matchedTransactions);resUpdatedAccounts.push(...updatedAccounts);- dispatch(getAccounts());+ dispatch(markAccountsDirty());return newTransactions.length > 0 || matchedTransactions.length > 0;}@@ -359,8 +359,8 @@ export const moveAccount = createAppAsyncThunk(`${sliceName}/moveAccount`,async ({ id, targetId }: MoveAccountPayload, { dispatch }) => {await send('account-move', { id, targetId });- dispatch(getAccounts());- dispatch(getPayees());+ dispatch(markAccountsDirty());+ dispatch(markPayeesDirty());},);diff --git a/packages/desktop-client/src/components/FinancesApp.tsx b/packages/desktop-client/src/components/FinancesApp.tsxindex 91ddabd9d7..d0c505526e 100644--- a/packages/desktop-client/src/components/FinancesApp.tsx+++ b/packages/desktop-client/src/components/FinancesApp.tsx@@ -86,7 +86,7 @@ export function FinancesApp() {const { t } = useTranslation();const accounts = useAccounts();- const accountsLoaded = useSelector(state => state.queries.accountsLoaded);+ const isAccountsLoaded = useSelector(state => state.queries.isAccountsLoaded);const [lastUsedVersion, setLastUsedVersion] = useLocalPref('flags.updateNotificationShownForVersion',@@ -224,7 +224,7 @@ export function FinancesApp() {<Routepath="/"element={- accountsLoaded ? (+ isAccountsLoaded ? (accounts.length > 0 ? (<Navigate to="/budget" replace />) : (diff --git a/packages/desktop-client/src/components/ManageRules.tsx b/packages/desktop-client/src/components/ManageRules.tsxindex e0d6f7548b..5414821a8a 100644--- a/packages/desktop-client/src/components/ManageRules.tsx+++ b/packages/desktop-client/src/components/ManageRules.tsx@@ -38,7 +38,7 @@ import {SelectedProvider,} from '@desktop-client/hooks/useSelected';import { pushModal } from '@desktop-client/modals/modalsSlice';-import { initiallyLoadPayees } from '@desktop-client/queries/queriesSlice';+import { getPayees } from '@desktop-client/queries/queriesSlice';import { useDispatch } from '@desktop-client/redux';export type FilterData = {@@ -197,7 +197,7 @@ export function ManageRules({await loadRules();setLoading(false);- await dispatch(initiallyLoadPayees());+ await dispatch(getPayees());}if (payeeId) {diff --git a/packages/desktop-client/src/components/accounts/Account.tsx b/packages/desktop-client/src/components/accounts/Account.tsxindex d0f27f235e..705698b8ff 100644--- a/packages/desktop-client/src/components/accounts/Account.tsx+++ b/packages/desktop-client/src/components/accounts/Account.tsx@@ -81,7 +81,7 @@ import {} from '@desktop-client/queries/pagedQuery';import {createPayee,- initiallyLoadPayees,+ getPayees,markAccountRead,reopenAccount,updateAccount,@@ -391,7 +391,7 @@ class AccountInternal extends PureComponent<// Important that any async work happens last so that the// listeners are set up synchronously- await this.props.dispatch(initiallyLoadPayees());+ await this.props.dispatch(getPayees());await this.fetchTransactions(this.state.filterConditions);// If there is a pending undo, apply it immediately (this happensdiff --git a/packages/desktop-client/src/components/budget/index.tsx b/packages/desktop-client/src/components/budget/index.tsxindex 0cf1f48ac6..6455923376 100644--- a/packages/desktop-client/src/components/budget/index.tsx+++ b/packages/desktop-client/src/components/budget/index.tsx@@ -27,14 +27,14 @@ import { addNotification } from '@desktop-client/notifications/notificationsSlicimport {applyBudgetAction,createCategory,- createGroup,+ createCategoryGroup,deleteCategory,- deleteGroup,+ deleteCategoryGroup,getCategories,moveCategory,moveCategoryGroup,updateCategory,- updateGroup,+ updateCategoryGroup,} from '@desktop-client/queries/queriesSlice';import { useDispatch } from '@desktop-client/redux';@@ -217,9 +217,9 @@ function BudgetInner(props: BudgetInnerProps) {const onSaveGroup = group => {if (group.id === 'new') {- dispatch(createGroup({ name: group.name }));+ dispatch(createCategoryGroup({ name: group.name }));} else {- dispatch(updateGroup({ group }));+ dispatch(updateCategoryGroup({ group }));}};@@ -242,14 +242,16 @@ function BudgetInner(props: BudgetInnerProps) {options: {group: id,onDelete: transferCategory => {- dispatch(deleteGroup({ id, transferId: transferCategory }));+ dispatch(+ deleteCategoryGroup({ id, transferId: transferCategory }),+ );},},},}),);} else {- dispatch(deleteGroup({ id }));+ dispatch(deleteCategoryGroup({ id }));}};diff --git a/packages/desktop-client/src/components/mobile/budget/BudgetPage.tsx b/packages/desktop-client/src/components/mobile/budget/BudgetPage.tsxindex 819be64cab..b26eb00d35 100644--- a/packages/desktop-client/src/components/mobile/budget/BudgetPage.tsx+++ b/packages/desktop-client/src/components/mobile/budget/BudgetPage.tsx@@ -45,11 +45,11 @@ import { collapseModals, pushModal } from '@desktop-client/modals/modalsSlice';import {applyBudgetAction,createCategory,- createGroup,+ createCategoryGroup,deleteCategory,- deleteGroup,+ deleteCategoryGroup,updateCategory,- updateGroup,+ updateCategoryGroup,} from '@desktop-client/queries/queriesSlice';import { useDispatch } from '@desktop-client/redux';import {@@ -139,7 +139,7 @@ export function BudgetPage() {onValidate: name => (!name ? 'Name is required.' : null),onSubmit: async name => {dispatch(collapseModals({ rootModalName: 'budget-page-menu' }));- dispatch(createGroup({ name }));+ dispatch(createCategoryGroup({ name }));},},},@@ -173,7 +173,7 @@ export function BudgetPage() {const onSaveGroup = useCallback(group => {- dispatch(updateGroup({ group }));+ dispatch(updateCategoryGroup({ group }));},[dispatch],);@@ -221,7 +221,10 @@ export function BudgetPage() {collapseModals({ rootModalName: 'category-group-menu' }),);dispatch(- deleteGroup({ id: groupId, transferId: transferCategory }),+ deleteCategoryGroup({+ id: groupId,+ transferId: transferCategory,+ }),);},},@@ -230,7 +233,7 @@ export function BudgetPage() {);} else {dispatch(collapseModals({ rootModalName: 'category-group-menu' }));- dispatch(deleteGroup({ id: groupId }));+ dispatch(deleteCategoryGroup({ id: groupId }));}},[categoryGroups, dispatch],diff --git a/packages/desktop-client/src/components/modals/ImportTransactionsModal/ImportTransactionsModal.jsx b/packages/desktop-client/src/components/modals/ImportTransactionsModal/ImportTransactionsModal.jsxindex aa614842cb..1c816b2e5f 100644--- a/packages/desktop-client/src/components/modals/ImportTransactionsModal/ImportTransactionsModal.jsx+++ b/packages/desktop-client/src/components/modals/ImportTransactionsModal/ImportTransactionsModal.jsx@@ -41,9 +41,9 @@ import { useCategories } from '@desktop-client/hooks/useCategories';import { useDateFormat } from '@desktop-client/hooks/useDateFormat';import { useSyncedPrefs } from '@desktop-client/hooks/useSyncedPrefs';import {- getPayees,importPreviewTransactions,importTransactions,+ reloadPayees,} from '@desktop-client/queries/queriesSlice';import { useDispatch } from '@desktop-client/redux';@@ -679,7 +679,7 @@ export function ImportTransactionsModal({}),).unwrap();if (didChange) {- await dispatch(getPayees());+ await dispatch(reloadPayees());}if (onImported) {diff --git a/packages/desktop-client/src/components/payees/ManagePayeesWithData.tsx b/packages/desktop-client/src/components/payees/ManagePayeesWithData.tsxindex bbad255d34..8f4abcbd8c 100644--- a/packages/desktop-client/src/components/payees/ManagePayeesWithData.tsx+++ b/packages/desktop-client/src/components/payees/ManagePayeesWithData.tsx@@ -10,10 +10,7 @@ import { ManagePayees } from './ManagePayees';import { usePayees } from '@desktop-client/hooks/usePayees';import { pushModal } from '@desktop-client/modals/modalsSlice';-import {- getPayees,- initiallyLoadPayees,-} from '@desktop-client/queries/queriesSlice';+import { getPayees, reloadPayees } from '@desktop-client/queries/queriesSlice';import { useDispatch } from '@desktop-client/redux';type ManagePayeesWithDataProps = {@@ -42,7 +39,7 @@ export function ManagePayeesWithData({useEffect(() => {async function loadData() {- await dispatch(initiallyLoadPayees());+ await dispatch(getPayees());await refetchRuleCounts();await refetchOrphanedPayees();}@@ -152,7 +149,7 @@ export function ManagePayeesWithData({);});- await dispatch(getPayees());+ await dispatch(reloadPayees());setOrphans(filtedOrphans);setRuleCounts({ value: ruleCounts.value });}}diff --git a/packages/desktop-client/src/components/rules/RuleEditor.tsx b/packages/desktop-client/src/components/rules/RuleEditor.tsxindex 5a2bea1be3..7fd47396c7 100644--- a/packages/desktop-client/src/components/rules/RuleEditor.tsx+++ b/packages/desktop-client/src/components/rules/RuleEditor.tsx@@ -75,7 +75,7 @@ import {SelectedProvider,} from '@desktop-client/hooks/useSelected';import { aqlQuery } from '@desktop-client/queries/aqlQuery';-import { initiallyLoadPayees } from '@desktop-client/queries/queriesSlice';+import { getPayees } from '@desktop-client/queries/queriesSlice';import { useDispatch } from '@desktop-client/redux';import { enableUndo, disableUndo } from '@desktop-client/undo';@@ -939,7 +939,7 @@ export function RuleEditor({);useEffect(() => {- dispatch(initiallyLoadPayees());+ dispatch(getPayees());// Disable undo while this modal is opendisableUndo();diff --git a/packages/desktop-client/src/components/tags/ManageTags.tsx b/packages/desktop-client/src/components/tags/ManageTags.tsxindex cb9dc8ae72..43811ec8be 100644--- a/packages/desktop-client/src/components/tags/ManageTags.tsx+++ b/packages/desktop-client/src/components/tags/ManageTags.tsx@@ -20,9 +20,9 @@ import {SelectedProvider,useSelected,} from '@desktop-client/hooks/useSelected';+import { useTags } from '@desktop-client/hooks/useTags';import { deleteAllTags, findTags } from '@desktop-client/queries/queriesSlice';import { useDispatch } from '@desktop-client/redux';-import { useTags } from '@desktop-client/style/tags';export function ManageTags() {const { t } = useTranslation();diff --git a/packages/desktop-client/src/components/tags/TagCreationRow.tsx b/packages/desktop-client/src/components/tags/TagCreationRow.tsxindex 53722c89be..120b0388b1 100644--- a/packages/desktop-client/src/components/tags/TagCreationRow.tsx+++ b/packages/desktop-client/src/components/tags/TagCreationRow.tsx@@ -22,9 +22,9 @@ import {useTableNavigator,} from '@desktop-client/components/table';import { useProperFocus } from '@desktop-client/hooks/useProperFocus';+import { useTagCSS } from '@desktop-client/hooks/useTagCSS';import { createTag } from '@desktop-client/queries/queriesSlice';import { useDispatch } from '@desktop-client/redux';-import { useTagCSS } from '@desktop-client/style/tags';type TagCreationRowProps = {tags: Tag[];diff --git a/packages/desktop-client/src/components/tags/TagEditor.tsx b/packages/desktop-client/src/components/tags/TagEditor.tsxindex 1c5bb51b63..2a4e3ef3c6 100644--- a/packages/desktop-client/src/components/tags/TagEditor.tsx+++ b/packages/desktop-client/src/components/tags/TagEditor.tsx@@ -5,9 +5,9 @@ import { ColorPicker } from '@actual-app/components/color-picker';import { type Tag } from 'loot-core/types/models';+import { useTagCSS } from '@desktop-client/hooks/useTagCSS';import { updateTag } from '@desktop-client/queries/queriesSlice';import { useDispatch } from '@desktop-client/redux';-import { useTagCSS } from '@desktop-client/style/tags';type TagEditorProps = {tag: Tag;diff --git a/packages/desktop-client/src/global-events.ts b/packages/desktop-client/src/global-events.tsindex 8c169dd543..e2b27c96e6 100644--- a/packages/desktop-client/src/global-events.ts+++ b/packages/desktop-client/src/global-events.ts@@ -10,7 +10,11 @@ import {addNotification,} from './notifications/notificationsSlice';import { loadPrefs } from './prefs/prefsSlice';-import { getAccounts, getCategories, getPayees } from './queries/queriesSlice';+import {+ reloadAccounts,+ reloadCategories,+ reloadPayees,+} from './queries/queriesSlice';import { type AppStore } from './redux/store';import * as syncEvents from './sync-events';@@ -54,7 +58,7 @@ export function handleGlobalEvents(store: AppStore) {tables.includes('category_groups') ||tables.includes('category_mapping')) {- promises.push(store.dispatch(getCategories()));+ promises.push(store.dispatch(reloadCategories()));}if (@@ -62,11 +66,11 @@ export function handleGlobalEvents(store: AppStore) {tables.includes('payees') ||tables.includes('payee_mapping')) {- promises.push(store.dispatch(getPayees()));+ promises.push(store.dispatch(reloadPayees()));}if (tables.includes('accounts')) {- promises.push(store.dispatch(getAccounts()));+ promises.push(store.dispatch(reloadAccounts()));}const tagged = undo.getTaggedState(undoTag);diff --git a/packages/desktop-client/src/hooks/useAccounts.ts b/packages/desktop-client/src/hooks/useAccounts.tsindex a8dbe8d88a..3af2a17a72 100644--- a/packages/desktop-client/src/hooks/useAccounts.ts+++ b/packages/desktop-client/src/hooks/useAccounts.ts@@ -7,14 +7,14 @@ import { useSelector, useDispatch } from '@desktop-client/redux';export function useAccounts() {const dispatch = useDispatch();- const accountsLoaded = useSelector(state => state.queries.accountsLoaded);const isInitialMount = useInitialMount();+ const isAccountsDirty = useSelector(state => state.queries.isAccountsDirty);useEffect(() => {- if (isInitialMount && !accountsLoaded) {+ if (isInitialMount || isAccountsDirty) {dispatch(getAccounts());}- }, [accountsLoaded, dispatch, isInitialMount]);+ }, [dispatch, isInitialMount, isAccountsDirty]);return useSelector(state => state.queries.accounts);}diff --git a/packages/desktop-client/src/hooks/useCategories.ts b/packages/desktop-client/src/hooks/useCategories.tsindex 23df8fd8c9..7a4a33462e 100644--- a/packages/desktop-client/src/hooks/useCategories.ts+++ b/packages/desktop-client/src/hooks/useCategories.ts@@ -7,14 +7,16 @@ import { useSelector, useDispatch } from '@desktop-client/redux';export function useCategories() {const dispatch = useDispatch();- const categoriesLoaded = useSelector(state => state.queries.categoriesLoaded);const isInitialMount = useInitialMount();+ const isCategoriesDirty = useSelector(+ state => state.queries.isCategoriesDirty,+ );useEffect(() => {- if (isInitialMount && !categoriesLoaded) {+ if (isInitialMount || isCategoriesDirty) {dispatch(getCategories());}- }, [categoriesLoaded, dispatch, isInitialMount]);+ }, [dispatch, isInitialMount, isCategoriesDirty]);return useSelector(state => state.queries.categories);}diff --git a/packages/desktop-client/src/hooks/usePayees.ts b/packages/desktop-client/src/hooks/usePayees.tsindex 525797a0f2..90c6e42a17 100644--- a/packages/desktop-client/src/hooks/usePayees.ts+++ b/packages/desktop-client/src/hooks/usePayees.ts@@ -10,32 +10,30 @@ import { useSelector, useDispatch } from '@desktop-client/redux';export function useCommonPayees() {const dispatch = useDispatch();- const commonPayeesLoaded = useSelector(- state => state.queries.commonPayeesLoaded,- );-const isInitialMount = useInitialMount();+ const isCommonPayeesDirty = useSelector(+ state => state.queries.isCommonPayeesDirty,+ );useEffect(() => {- if (isInitialMount && !commonPayeesLoaded) {+ if (isInitialMount || isCommonPayeesDirty) {dispatch(getCommonPayees());}- }, [commonPayeesLoaded, dispatch, isInitialMount]);+ }, [dispatch, isInitialMount, isCommonPayeesDirty]);return useSelector(state => state.queries.commonPayees);}export function usePayees() {const dispatch = useDispatch();- const payeesLoaded = useSelector(state => state.queries.payeesLoaded);-const isInitialMount = useInitialMount();+ const isPayeesDirty = useSelector(state => state.queries.isPayeesDirty);useEffect(() => {- if (isInitialMount && !payeesLoaded) {+ if (isInitialMount || isPayeesDirty) {dispatch(getPayees());}- }, [dispatch, isInitialMount, payeesLoaded]);+ }, [dispatch, isInitialMount, isPayeesDirty]);return useSelector(state => state.queries.payees);}diff --git a/packages/desktop-client/src/style/tags.ts b/packages/desktop-client/src/hooks/useTagCSS.tssimilarity index 79%rename from packages/desktop-client/src/style/tags.tsrename to packages/desktop-client/src/hooks/useTagCSS.tsindex 5f7af04d59..a20a4ec174 100644--- a/packages/desktop-client/src/style/tags.ts+++ b/packages/desktop-client/src/hooks/useTagCSS.ts@@ -1,27 +1,47 @@-import React, { useCallback, useEffect } from 'react';+import React, { useCallback } from 'react';import { theme as themeStyle } from '@actual-app/components/theme';import { css } from '@emotion/css';import { type Theme } from 'loot-core/types/prefs';-import { useTheme } from './theme';+import { useTags } from './useTags';-import { getTags } from '@desktop-client/queries/queriesSlice';-import { useDispatch, useSelector } from '@desktop-client/redux';+import { useTheme } from '@desktop-client/style';-export function useTags() {- const dispatch = useDispatch();- const tags = useSelector(state => state.queries.tags);- const tagsLoaded = useSelector(state => state.queries.tagsLoaded);+export function useTagCSS() {+ const tags = useTags();+ const [theme] = useTheme();- useEffect(() => {- if (!tagsLoaded) {- dispatch(getTags());- }- }, [tagsLoaded, dispatch]);+ return useCallback(+ (+ tag: string,+ options: { color?: string | null; compact?: boolean } = {},+ ) => {+ const [color, backgroundColor, backgroundColorHovered] = getTagCSSColors(+ theme,+ // fallback strategy: options color > tag color > default color > theme color (undefined)+ options.color ?? tags.find(t => t.tag === tag)?.color,+ );- return tags;+ return css({+ display: 'inline-flex',+ padding: options.compact ? '0px 7px' : '3px 7px',+ borderRadius: 16,+ userSelect: 'none',+ backgroundColor,+ color,+ cursor: 'pointer',+ '&[data-hovered]': {+ backgroundColor: backgroundColorHovered,+ },+ '&[data-pressed]': {+ backgroundColor: backgroundColorHovered,+ },+ });+ },+ [theme, tags],+ );}function getContrastedColor(hexcolor: string) {@@ -63,38 +83,3 @@ function getTagCSSColors(theme: Theme, color?: string | null) {];}}--export function useTagCSS() {- const tags = useTags();- const [theme] = useTheme();-- return useCallback(- (- tag: string,- options: { color?: string | null; compact?: boolean } = {},- ) => {- const [color, backgroundColor, backgroundColorHovered] = getTagCSSColors(- theme,- // fallback strategy: options color > tag color > default color > theme color (undefined)- options.color ?? tags.find(t => t.tag === tag)?.color,- );-- return css({- display: 'inline-flex',- padding: options.compact ? '0px 7px' : '3px 7px',- borderRadius: 16,- userSelect: 'none',- backgroundColor,- color,- cursor: 'pointer',- '&[data-hovered]': {- backgroundColor: backgroundColorHovered,- },- '&[data-pressed]': {- backgroundColor: backgroundColorHovered,- },- });- },- [theme, tags],- );-}diff --git a/packages/desktop-client/src/hooks/useTags.ts b/packages/desktop-client/src/hooks/useTags.tsnew file mode 100644index 0000000000..85577bbf99--- /dev/null+++ b/packages/desktop-client/src/hooks/useTags.ts@@ -0,0 +1,20 @@+import { useEffect } from 'react';++import { useInitialMount } from './useInitialMount';++import { getTags } from '@desktop-client/queries/queriesSlice';+import { useDispatch, useSelector } from '@desktop-client/redux';++export function useTags() {+ const dispatch = useDispatch();+ const isInitialMount = useInitialMount();+ const isTagsDirty = useSelector(state => state.queries.isTagsDirty);++ useEffect(() => {+ if (isInitialMount || isTagsDirty) {+ dispatch(getTags());+ }+ }, [dispatch, isInitialMount, isTagsDirty]);++ return useSelector(state => state.queries.tags);+}diff --git a/packages/desktop-client/src/notes/DesktopTaggedNotes.tsx b/packages/desktop-client/src/notes/DesktopTaggedNotes.tsxindex 4008dff2f7..55f98af8f3 100644--- a/packages/desktop-client/src/notes/DesktopTaggedNotes.tsx+++ b/packages/desktop-client/src/notes/DesktopTaggedNotes.tsx@@ -3,7 +3,7 @@ import React from 'react';import { Button } from '@actual-app/components/button';import { View } from '@actual-app/components/view';-import { useTagCSS } from '@desktop-client/style/tags';+import { useTagCSS } from '@desktop-client/hooks/useTagCSS';type DesktopTaggedNotesProps = {content: string;diff --git a/packages/desktop-client/src/notes/MobileTaggedNotes.tsx b/packages/desktop-client/src/notes/MobileTaggedNotes.tsxindex 9332bfdf67..38601dd959 100644--- a/packages/desktop-client/src/notes/MobileTaggedNotes.tsx+++ b/packages/desktop-client/src/notes/MobileTaggedNotes.tsx@@ -2,7 +2,7 @@ import React from 'react';import { Text } from '@actual-app/components/text';-import { useTagCSS } from '@desktop-client/style/tags';+import { useTagCSS } from '@desktop-client/hooks/useTagCSS';type MobileTaggedNotesProps = {content: string;diff --git a/packages/desktop-client/src/queries/queriesSlice.ts b/packages/desktop-client/src/queries/queriesSlice.tsindex b552bedc29..344321e685 100644--- a/packages/desktop-client/src/queries/queriesSlice.ts+++ b/packages/desktop-client/src/queries/queriesSlice.ts@@ -34,15 +34,25 @@ type QueriesState = {lastTransaction: TransactionEntity | null;updatedAccounts: Array<AccountEntity['id']>;accounts: AccountEntity[];- accountsLoaded: boolean;+ isAccountsLoading: boolean;+ isAccountsLoaded: boolean;+ isAccountsDirty: boolean;categories: CategoryViews;- categoriesLoaded: boolean;- commonPayeesLoaded: boolean;+ isCategoriesLoading: boolean;+ isCategoriesLoaded: boolean;+ isCategoriesDirty: boolean;commonPayees: PayeeEntity[];+ isCommonPayeesLoading: boolean;+ isCommonPayeesLoaded: boolean;+ isCommonPayeesDirty: boolean;payees: PayeeEntity[];- payeesLoaded: boolean;+ isPayeesLoading: boolean;+ isPayeesLoaded: boolean;+ isPayeesDirty: boolean;tags: Tag[];- tagsLoaded: boolean;+ isTagsLoading: boolean;+ isTagsLoaded: boolean;+ isTagsDirty: boolean;};const initialState: QueriesState = {@@ -51,18 +61,28 @@ const initialState: QueriesState = {lastTransaction: null,updatedAccounts: [],accounts: [],- accountsLoaded: false,+ isAccountsLoading: false,+ isAccountsLoaded: false,+ isAccountsDirty: false,categories: {grouped: [],list: [],},- categoriesLoaded: false,+ isCategoriesLoading: false,+ isCategoriesLoaded: false,+ isCategoriesDirty: false,commonPayees: [],- commonPayeesLoaded: false,+ isCommonPayeesLoading: false,+ isCommonPayeesLoaded: false,+ isCommonPayeesDirty: false,payees: [],- payeesLoaded: false,+ isPayeesLoading: false,+ isPayeesLoaded: false,+ isPayeesDirty: false,tags: [],- tagsLoaded: false,+ isTagsLoading: false,+ isTagsLoaded: false,+ isTagsDirty: false,};type SetNewTransactionsPayload = {@@ -125,41 +145,136 @@ const queriesSlice = createSlice({id => id !== action.payload.id,);},+ markAccountsDirty(state) {+ _markAccountsDirty(state);+ },+ markCategoriesDirty(state) {+ _markCategoriesDirty(state);+ },+ markPayeesDirty(state) {+ _markPayeesDirty(state);+ },+ markTagsDirty(state) {+ _markTagsDirty(state);+ },},extraReducers: builder => {// Accounts- builder.addCase(updateAccount.fulfilled, (state, action) => {- const payloadAccount = action.payload;- state.accounts = state.accounts.map(account => {- if (account.id === payloadAccount.id) {- return { ...account, ...payloadAccount };- }- return account;- });++ builder.addCase(createAccount.fulfilled, _markAccountsDirty);+ builder.addCase(updateAccount.fulfilled, _markAccountsDirty);+ builder.addCase(closeAccount.fulfilled, _markAccountsDirty);+ builder.addCase(reopenAccount.fulfilled, _markAccountsDirty);++ builder.addCase(reloadAccounts.fulfilled, (state, action) => {+ _loadAccounts(state, action.payload);+ });++ builder.addCase(reloadAccounts.rejected, state => {+ state.isAccountsLoading = false;+ });++ builder.addCase(reloadAccounts.pending, state => {+ state.isAccountsLoading = true;});builder.addCase(getAccounts.fulfilled, (state, action) => {- state.accounts = action.payload;- state.accountsLoaded = true;+ _loadAccounts(state, action.payload);+ });++ builder.addCase(getAccounts.rejected, state => {+ state.isAccountsLoading = false;+ });++ builder.addCase(getAccounts.pending, state => {+ state.isAccountsLoading = true;});// Categories+ builder.addCase(createCategoryGroup.fulfilled, _markCategoriesDirty);+ builder.addCase(updateCategoryGroup.fulfilled, _markCategoriesDirty);+ builder.addCase(deleteCategoryGroup.fulfilled, _markCategoriesDirty);+ builder.addCase(createCategory.fulfilled, _markCategoriesDirty);+ builder.addCase(updateCategory.fulfilled, _markCategoriesDirty);+ builder.addCase(deleteCategory.fulfilled, _markCategoriesDirty);+ builder.addCase(moveCategoryGroup.fulfilled, _markCategoriesDirty);+ builder.addCase(moveCategory.fulfilled, _markCategoriesDirty);++ builder.addCase(reloadCategories.fulfilled, (state, action) => {+ _loadCategories(state, action.payload);+ });++ builder.addCase(reloadCategories.rejected, state => {+ state.isCategoriesLoading = false;+ });++ builder.addCase(reloadCategories.pending, state => {+ state.isCategoriesLoading = true;+ });+builder.addCase(getCategories.fulfilled, (state, action) => {- state.categories = action.payload;- state.categoriesLoaded = true;+ _loadCategories(state, action.payload);+ });++ builder.addCase(getCategories.rejected, state => {+ state.isCategoriesLoading = false;+ });++ builder.addCase(getCategories.pending, state => {+ state.isCategoriesLoading = true;});// Payees+ 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) => {- state.commonPayees = action.payload;- state.commonPayeesLoaded = true;+ _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) => {- state.payees = action.payload;- state.payeesLoaded = true;+ _loadPayees(state, action.payload);+ });++ builder.addCase(getPayees.rejected, state => {+ state.isPayeesLoading = false;+ });++ builder.addCase(getPayees.pending, state => {+ state.isPayeesLoading = true;});// App@@ -168,30 +283,45 @@ const queriesSlice = createSlice({// Tags- builder.addCase(getTags.fulfilled, (state, action) => {- state.tags = action.payload;- state.tagsLoaded = true;+ builder.addCase(createTag.fulfilled, _markTagsDirty);+ builder.addCase(deleteTag.fulfilled, _markTagsDirty);+ builder.addCase(deleteAllTags.fulfilled, _markTagsDirty);+ builder.addCase(updateTag.fulfilled, _markTagsDirty);++ builder.addCase(reloadTags.fulfilled, (state, action) => {+ _loadTags(state, action.payload);});- builder.addCase(createTag.fulfilled, (state, action) => {- state.tags.push(action.payload);+ builder.addCase(reloadTags.rejected, state => {+ state.isTagsLoading = false;});- builder.addCase(deleteTag.fulfilled, (state, action) => {- state.tags = state.tags.filter(tag => tag.id !== action.payload);+ builder.addCase(reloadTags.pending, state => {+ state.isTagsLoading = true;});- builder.addCase(deleteAllTags.fulfilled, (state, action) => {- state.tags = state.tags.filter(tag => !action.payload.includes(tag.id));+ builder.addCase(getTags.fulfilled, (state, action) => {+ _loadTags(state, action.payload);+ });++ builder.addCase(getTags.rejected, state => {+ state.isTagsLoading = false;});- builder.addCase(updateTag.fulfilled, (state, action) => {- const tagIdx = state.tags.findIndex(tag => tag.id === action.payload.id);- state.tags[tagIdx] = action.payload;+ builder.addCase(getTags.pending, state => {+ state.isTagsLoading = true;});builder.addCase(findTags.fulfilled, (state, action) => {- state.tags = action.payload;+ _loadTags(state, action.payload);+ });++ builder.addCase(findTags.rejected, state => {+ state.isTagsLoading = false;+ });++ builder.addCase(findTags.pending, state => {+ state.isTagsLoading = true;});},});@@ -271,6 +401,25 @@ export const getAccounts = createAppAsyncThunk(const accounts = (await send('accounts-get')) as AccountEntity[];return accounts;},+ {+ condition: (_, { getState }) => {+ const { queries } = getState();+ return (+ !queries.isAccountsLoading &&+ (queries.isAccountsDirty || !queries.isAccountsLoaded)+ );+ },+ },+);++export const reloadAccounts = createAppAsyncThunk(+ `${sliceName}/reloadAccounts`,+ async () => {+ // TODO: Force cast to AccountEntity.+ // Server is currently returning the DB model it should return the entity model instead.+ const accounts = (await send('accounts-get')) as AccountEntity[];+ return accounts;+ },);// Category actions@@ -279,8 +428,8 @@ type CreateCategoryGroupPayload = {name: CategoryGroupEntity['name'];};-export const createGroup = createAppAsyncThunk(- `${sliceName}/createGroup`,+export const createCategoryGroup = createAppAsyncThunk(+ `${sliceName}/createCategoryGroup`,async ({ name }: CreateCategoryGroupPayload) => {const id = await send('category-group-create', { name });return id;@@ -291,8 +440,8 @@ type UpdateCategoryGroupPayload = {group: CategoryGroupEntity;};-export const updateGroup = createAppAsyncThunk(- `${sliceName}/updateGroup`,+export const updateCategoryGroup = createAppAsyncThunk(+ `${sliceName}/updateCategoryGroup`,async ({ group }: UpdateCategoryGroupPayload) => {// Strip off the categories field if it exist. It's not a real db// field but groups have this extra field in the client most of the time@@ -306,8 +455,8 @@ type DeleteCategoryGroupPayload = {transferId?: CategoryGroupEntity['id'];};-export const deleteGroup = createAppAsyncThunk(- `${sliceName}/deleteGroup`,+export const deleteCategoryGroup = createAppAsyncThunk(+ `${sliceName}/deleteCategoryGroup`,async ({ id, transferId }: DeleteCategoryGroupPayload) => {await send('category-group-delete', { id, transferId });},@@ -408,6 +557,23 @@ export const getCategories = createAppAsyncThunk(const categories: CategoryViews = await send('get-categories');return categories;},+ {+ condition: (_, { getState }) => {+ const { queries } = getState();+ return (+ !queries.isCategoriesLoading &&+ (queries.isCategoriesDirty || !queries.isCategoriesLoaded)+ );+ },+ },+);++export const reloadCategories = createAppAsyncThunk(+ `${sliceName}/reloadCategories`,+ async () => {+ const categories: CategoryViews = await send('get-categories');+ return categories;+ },);// Payee actions@@ -426,18 +592,25 @@ export const createPayee = createAppAsyncThunk(},);-export const initiallyLoadPayees = createAppAsyncThunk(- `${sliceName}/initiallyLoadPayees`,- async (_, { dispatch, getState }) => {- const queriesState = getState().queries;- if (queriesState.payees.length === 0) {- dispatch(getPayees());- }+export const getCommonPayees = createAppAsyncThunk(+ `${sliceName}/getCommonPayees`,+ async () => {+ const payees: PayeeEntity[] = await send('common-payees-get');+ return payees;+ },+ {+ condition: (_, { getState }) => {+ const { queries } = getState();+ return (+ !queries.isCommonPayeesLoading &&+ (queries.isCommonPayeesDirty || !queries.isCommonPayeesLoaded)+ );+ },},);-export const getCommonPayees = createAppAsyncThunk(- `${sliceName}/getCommonPayees`,+export const reloadCommonPayees = createAppAsyncThunk(+ `${sliceName}/reloadCommonPayees`,async () => {const payees: PayeeEntity[] = await send('common-payees-get');return payees;@@ -450,12 +623,48 @@ export const getPayees = createAppAsyncThunk(const payees: PayeeEntity[] = await send('payees-get');return payees;},+ {+ condition: (_, { getState }) => {+ const { queries } = getState();+ return (+ !queries.isPayeesLoading &&+ (queries.isPayeesDirty || !queries.isPayeesLoaded)+ );+ },+ },);-export const getTags = createAppAsyncThunk(`${sliceName}/getTags`, async () => {- const tags: Tag[] = await send('tags-get');- return tags;-});+export const reloadPayees = createAppAsyncThunk(+ `${sliceName}/reloadPayees`,+ async () => {+ const payees: PayeeEntity[] = await send('payees-get');+ return payees;+ },+);++export const getTags = createAppAsyncThunk(+ `${sliceName}/getTags`,+ async () => {+ const tags: Tag[] = await send('tags-get');+ return tags;+ },+ {+ condition: (_, { getState }) => {+ const { queries } = getState();+ return (+ !queries.isTagsLoading && (queries.isTagsDirty || !queries.isTagsLoaded)+ );+ },+ },+);++export const reloadTags = createAppAsyncThunk(+ `${sliceName}/reloadTags`,+ async () => {+ const tags: Tag[] = await send('tags-get');+ return tags;+ },+);export const createTag = createAppAsyncThunk(`${sliceName}/createTag`,@@ -492,8 +701,8 @@ export const updateTag = createAppAsyncThunk(export const findTags = createAppAsyncThunk(`${sliceName}/findTags`,async () => {- const id = await send('tags-find');- return id;+ const tags: Tag[] = await send('tags-find');+ return tags;},);@@ -941,6 +1150,7 @@ export const actions = {...queriesSlice.actions,updateAccount,getAccounts,+ reloadAccounts,closeAccount,reopenAccount,getCategories,@@ -951,21 +1161,85 @@ export const actions = {importTransactions,applyBudgetAction,createAccount,- createGroup,- updateGroup,- deleteGroup,+ createCategoryGroup,+ updateCategoryGroup,+ deleteCategoryGroup,createCategory,updateCategory,deleteCategory,moveCategory,moveCategoryGroup,- initiallyLoadPayees,getTags,};export const {markAccountRead,+ markAccountsDirty,+ markCategoriesDirty,+ markPayeesDirty,+ markTagsDirty,setLastTransaction,updateNewTransactions,setNewTransactions,} = actions;++function _loadAccounts(+ state: QueriesState,+ accounts: QueriesState['accounts'],+) {+ state.accounts = accounts;+ state.isAccountsLoading = false;+ state.isAccountsLoaded = true;+ state.isAccountsDirty = false;+}++function _markAccountsDirty(state: QueriesState) {+ state.isAccountsDirty = true;+}++function _loadCategories(+ state: QueriesState,+ categories: QueriesState['categories'],+) {+ state.categories = categories;+ state.isCategoriesLoading = false;+ state.isCategoriesLoaded = true;+ state.isCategoriesDirty = false;+}++function _markCategoriesDirty(state: QueriesState) {+ state.isCategoriesDirty = true;+}++function _loadCommonPayees(+ state: QueriesState,+ commonPayees: QueriesState['commonPayees'],+) {+ state.commonPayees = commonPayees;+ state.isCommonPayeesLoading = false;+ state.isCommonPayeesLoaded = true;+ state.isCommonPayeesDirty = false;+}++function _loadPayees(state: QueriesState, payees: QueriesState['payees']) {+ state.payees = payees;+ state.isPayeesLoading = false;+ state.isPayeesLoaded = true;+ state.isPayeesDirty = false;+}++function _markPayeesDirty(state: QueriesState) {+ state.isCommonPayeesDirty = true;+ state.isPayeesDirty = true;+}++function _loadTags(state: QueriesState, tags: QueriesState['tags']) {+ state.tags = tags;+ state.isTagsLoading = false;+ state.isTagsLoaded = true;+ state.isTagsDirty = false;+}++function _markTagsDirty(state: QueriesState) {+ state.isTagsDirty = true;+}diff --git a/packages/desktop-client/src/sync-events.ts b/packages/desktop-client/src/sync-events.tsindex 5f3ff4a74e..841b974473 100644--- a/packages/desktop-client/src/sync-events.ts+++ b/packages/desktop-client/src/sync-events.ts@@ -11,7 +11,11 @@ import {type Notification,} from './notifications/notificationsSlice';import { loadPrefs } from './prefs/prefsSlice';-import { getAccounts, getCategories, getPayees } from './queries/queriesSlice';+import {+ reloadAccounts,+ reloadCategories,+ reloadPayees,+} from './queries/queriesSlice';import { type AppStore } from './redux/store';import { signOut } from './users/usersSlice';@@ -67,7 +71,7 @@ export function listenForSyncEvent(store: AppStore) {tables.includes('category_groups') ||tables.includes('category_mapping')) {- store.dispatch(getCategories());+ store.dispatch(reloadCategories());}if (@@ -76,11 +80,11 @@ export function listenForSyncEvent(store: AppStore) {tables.includes('payees') ||tables.includes('payee_mapping')) {- store.dispatch(getPayees());+ store.dispatch(reloadPayees());}if (tables.includes('accounts')) {- store.dispatch(getAccounts());+ store.dispatch(reloadAccounts());}} else if (event.type === 'error') {let notif: Notification | null = null;diff --git a/upcoming-release-notes/5579.md b/upcoming-release-notes/5579.mdnew file mode 100644index 0000000000..1f02681bc7--- /dev/null+++ b/upcoming-release-notes/5579.md@@ -0,0 +1,6 @@+---+category: Bugfix+authors: [joel-jeremy]+---++Prevent unnecessary calls to DB if same redux action is already pending