Skip to content

A local-first personal finance app

enable new lint rules (#9248)

Matt Fiddamanbde50c3bee3e
diff --git a/.oxlintrc.json b/.oxlintrc.json
index f6a83d9a0d..19e42f7611 100644
--- a/.oxlintrc.json
+++ b/.oxlintrc.json
@@ -1,6 +1,6 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
- "plugins": ["react", "typescript", "import", "jsx-a11y"],
+ "plugins": ["react", "typescript", "import", "jsx-a11y", "node", "vitest"],
// Vendored third-party agent skill scripts; not maintained in this repo
"ignorePatterns": ["**/skills/impeccable/**"],
"jsPlugins": [
@@ -80,6 +80,7 @@
// Typescript rules
"typescript/ban-ts-comment": ["error"],
+ "typescript/no-generated-empty-object-type": "error",
"typescript/consistent-type-definitions": ["error", "type"],
"typescript/consistent-type-imports": [
"error",
@@ -170,6 +171,50 @@
"react/style-prop-object": "error",
"react/jsx-boolean-value": "error",
+ "react/capitalized-calls": "error",
+ "react/hooks": "error",
+ "react/immutability": "error",
+ "react/memo-dependencies": "error",
+ "react/no-deriving-state-in-effects": "error",
+ "react/preserve-manual-memoization": "error",
+ "react/purity": "error",
+ "react/rule-suppression": "error",
+ "react/set-state-in-render": "error",
+ "react/exhaustive-effect-dependencies": "warn",
+ "react/refs": "warn",
+ "react/set-state-in-effect": "warn",
+
+ // Node rules
+ "node/no-exports-assign": "error",
+
+ // Vitest rules
+ "vitest/expect-expect": [
+ "error",
+ {
+ "assertFunctionNames": [
+ "expect",
+ "expectTypeOf",
+ "assert",
+ "assertType",
+ "tracer.expect",
+ "expect*"
+ ]
+ }
+ ],
+ "vitest/hoisted-apis-on-top": "error",
+ "vitest/no-conditional-tests": "error",
+ "vitest/no-disabled-tests": "warn",
+ "vitest/no-focused-tests": "error",
+ "vitest/no-identical-title": "error",
+ "vitest/no-standalone-expect": "error",
+ "vitest/valid-describe-callback": "error",
+ "vitest/valid-expect": ["error", { "maxArgs": 2 }],
+ "vitest/valid-expect-in-promise": "error",
+ "vitest/valid-title": ["error", { "ignoreTypeOfTestName": true }],
+ "vitest/prefer-snapshot-hint": "off",
+ "vitest/require-mock-type-parameters": "off",
+ "vitest/require-to-throw-message": "off",
+
// ESLint rules
"eslint/array-callback-return": "error",
"eslint/curly": ["error", "multi-line", "consistent"],
@@ -367,11 +412,11 @@
"eslint/no-undef": "error",
"eslint/no-unused-expressions": "error",
"eslint/no-return-assign": "error",
- "eslint/no-unused-vars": "error"
+ "eslint/no-unused-vars": "error",
+ "eslint/prefer-promise-reject-errors": "error"
},
"overrides": [
{
- // CommonJS files that cannot use ESM imports.
"files": ["**/*.cjs", "packages/eslint-plugin-actual/lib/**/*.js"],
"rules": {
"typescript/no-var-requires": "off"
diff --git a/packages/cli/src/lock.test.ts b/packages/cli/src/lock.test.ts
index eea37af962..c9aa1610db 100644
--- a/packages/cli/src/lock.test.ts
+++ b/packages/cli/src/lock.test.ts
@@ -66,6 +66,7 @@ describe('acquireExclusive', () => {
const release1 = await acquireExclusive(dir, { timeoutMs: 1000 });
await release1();
const release2 = await acquireExclusive(dir, { timeoutMs: 1000 });
+ expect(release2).toBeTypeOf('function');
await release2();
});
diff --git a/packages/desktop-client/src/components/App.tsx b/packages/desktop-client/src/components/App.tsx
index 2e8984c2a6..eda41979cd 100644
--- a/packages/desktop-client/src/components/App.tsx
+++ b/packages/desktop-client/src/components/App.tsx
@@ -1,4 +1,4 @@
-import React, { useEffect, useState } from 'react';
+import React, { useEffect, useRef, useState } from 'react';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { ErrorBoundary, useErrorBoundary } from 'react-error-boundary';
@@ -58,7 +58,13 @@ function AppInner() {
setI18NextLanguage(null);
}, []);
+ const isInitialized = useRef(false);
useEffect(() => {
+ if (isInitialized.current) {
+ return;
+ }
+ isInitialized.current = true;
+
const maybeUpdate = async <T,>(cb?: () => T): Promise<T | void> => {
if (global.Actual.isUpdateReadyForDownload()) {
dispatch(
@@ -126,9 +132,7 @@ function AppInner() {
}
initAll().catch(showErrorBoundary);
- // Removed cloudFileId & t from dependencies to prevent hard crash when closing budget in Electron
- // oxlint-disable-next-line react-hooks/exhaustive-deps
- }, [dispatch, showErrorBoundary]);
+ }, [cloudFileId, dispatch, showErrorBoundary, t]);
useEffect(() => {
if (userData?.tokenExpired) {
diff --git a/packages/desktop-client/src/components/autocomplete/Autocomplete.tsx b/packages/desktop-client/src/components/autocomplete/Autocomplete.tsx
index 53d0d34bd3..f165a05f55 100644
--- a/packages/desktop-client/src/components/autocomplete/Autocomplete.tsx
+++ b/packages/desktop-client/src/components/autocomplete/Autocomplete.tsx
@@ -240,6 +240,19 @@ function SingleAutocomplete<T extends AutocompleteItem>({
const [selectedItem, setSelectedItem] = useState(() =>
findItem(strict, suggestions, initialValue),
);
+ const [prevSelectionInputs, setPrevSelectionInputs] = useState({
+ initialValue,
+ suggestions,
+ strict,
+ });
+ if (
+ prevSelectionInputs.initialValue !== initialValue ||
+ prevSelectionInputs.suggestions !== suggestions ||
+ prevSelectionInputs.strict !== strict
+ ) {
+ setPrevSelectionInputs({ initialValue, suggestions, strict });
+ setSelectedItem(findItem(strict, suggestions, initialValue));
+ }
const [value, setValue] = useState(
selectedItem ? getItemName(selectedItem) : '',
);
@@ -297,12 +310,6 @@ function SingleAutocomplete<T extends AutocompleteItem>({
},
};
- // Update the selected item if the suggestion list or initial
- // input value has changed
- useEffect(() => {
- setSelectedItem(findItem(strict, suggestions, initialValue));
- }, [initialValue, suggestions, strict]);
-
// Sometimes (khem, khem.. on mobile) we want to force update
// the "value" field (which is also used as a search term) if
// the initial value changes.
diff --git a/packages/desktop-client/src/components/banksync/useBuiltInBankSyncProviders.ts b/packages/desktop-client/src/components/banksync/useBuiltInBankSyncProviders.ts
index d0b645c767..bcf539158f 100644
--- a/packages/desktop-client/src/components/banksync/useBuiltInBankSyncProviders.ts
+++ b/packages/desktop-client/src/components/banksync/useBuiltInBankSyncProviders.ts
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { send } from '@actual-app/core/platform/client/connection';
@@ -113,17 +113,6 @@ export function useBuiltInBankSyncProviders({
const { cloudFileId, isAdmin, isFileOwner } = useCurrentAccess();
const canConfigureProviders = isAdmin;
- const [isGoCardlessSetupComplete, setIsGoCardlessSetupComplete] = useState<
- boolean | null
- >(null);
- const [isSimpleFinSetupComplete, setIsSimpleFinSetupComplete] = useState<
- boolean | null
- >(null);
- const [isEnableBankingSetupComplete, setIsEnableBankingSetupComplete] =
- useState<boolean | null>(null);
- const [isAkahuSetupComplete, setIsAkahuSetupComplete] = useState<
- boolean | null
- >(null);
const [loadingSimpleFinAccounts, setLoadingSimpleFinAccounts] =
useState(false);
const [loadingAkahuAccounts, setLoadingAkahuAccounts] = useState(false);
@@ -137,21 +126,44 @@ export function useBuiltInBankSyncProviders({
const { configuredEnableBanking, isLoading: isEnableBankingLoading } =
useEnableBankingStatus(enableBankingEnabled);
- useEffect(() => {
+ const [isGoCardlessSetupComplete, setIsGoCardlessSetupComplete] = useState<
+ boolean | null
+ >(configuredGoCardless);
+ const [prevConfiguredGoCardless, setPrevConfiguredGoCardless] =
+ useState(configuredGoCardless);
+ if (configuredGoCardless !== prevConfiguredGoCardless) {
+ setPrevConfiguredGoCardless(configuredGoCardless);
setIsGoCardlessSetupComplete(configuredGoCardless);
- }, [configuredGoCardless]);
+ }
- useEffect(() => {
+ const [isSimpleFinSetupComplete, setIsSimpleFinSetupComplete] = useState<
+ boolean | null
+ >(configuredSimpleFin);
+ const [prevConfiguredSimpleFin, setPrevConfiguredSimpleFin] =
+ useState(configuredSimpleFin);
+ if (configuredSimpleFin !== prevConfiguredSimpleFin) {
+ setPrevConfiguredSimpleFin(configuredSimpleFin);
setIsSimpleFinSetupComplete(configuredSimpleFin);
- }, [configuredSimpleFin]);
+ }
- useEffect(() => {
+ const [isEnableBankingSetupComplete, setIsEnableBankingSetupComplete] =
+ useState<boolean | null>(configuredEnableBanking);
+ const [prevConfiguredEnableBanking, setPrevConfiguredEnableBanking] =
+ useState(configuredEnableBanking);
+ if (configuredEnableBanking !== prevConfiguredEnableBanking) {
+ setPrevConfiguredEnableBanking(configuredEnableBanking);
setIsEnableBankingSetupComplete(configuredEnableBanking);
- }, [configuredEnableBanking]);
+ }
- useEffect(() => {
+ const [isAkahuSetupComplete, setIsAkahuSetupComplete] = useState<
+ boolean | null
+ >(configuredAkahu);
+ const [prevConfiguredAkahu, setPrevConfiguredAkahu] =
+ useState(configuredAkahu);
+ if (configuredAkahu !== prevConfiguredAkahu) {
+ setPrevConfiguredAkahu(configuredAkahu);
setIsAkahuSetupComplete(configuredAkahu);
- }, [configuredAkahu]);
+ }
const onGoCardlessInit = useCallback(() => {
dispatch(
diff --git a/packages/desktop-client/src/components/budget/goals/editor/BySaveAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/BySaveAutomation.tsx
index 6ffdf0cdc2..7e1585954f 100644
--- a/packages/desktop-client/src/components/budget/goals/editor/BySaveAutomation.tsx
+++ b/packages/desktop-client/src/components/budget/goals/editor/BySaveAutomation.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from 'react';
+import { useState } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { SvgInformationCircle } from '@actual-app/components/icons/v2';
@@ -42,10 +42,12 @@ export const BySaveAutomation = ({
const committedRepeat = template.repeat ?? 1;
const [rawRepeat, setRawRepeat] = useState(String(committedRepeat));
-
- useEffect(() => {
+ const [prevCommittedRepeat, setPrevCommittedRepeat] =
+ useState(committedRepeat);
+ if (committedRepeat !== prevCommittedRepeat) {
+ setPrevCommittedRepeat(committedRepeat);
setRawRepeat(String(committedRepeat));
- }, [committedRepeat]);
+ }
const onRepeatChange = (value: string) => {
setRawRepeat(value);
diff --git a/packages/desktop-client/src/components/budget/goals/editor/FixedAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/FixedAutomation.tsx
index aca86db17a..7000325566 100644
--- a/packages/desktop-client/src/components/budget/goals/editor/FixedAutomation.tsx
+++ b/packages/desktop-client/src/components/budget/goals/editor/FixedAutomation.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from 'react';
+import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Input } from '@actual-app/components/input';
@@ -44,9 +44,11 @@ export const FixedAutomation = ({
const [rawPeriodAmount, setRawPeriodAmount] = useState(String(periodAmount));
// Resync when a different automation row is selected (the component
// instance is reused across rows).
- useEffect(() => {
+ const [prevPeriodAmount, setPrevPeriodAmount] = useState(periodAmount);
+ if (periodAmount !== prevPeriodAmount) {
+ setPrevPeriodAmount(periodAmount);
setRawPeriodAmount(String(periodAmount));
- }, [periodAmount]);
+ }
const onPeriodAmountChange = (value: string) => {
setRawPeriodAmount(value);
diff --git a/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomation.tsx
index 34163ef155..6587331266 100644
--- a/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomation.tsx
+++ b/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomation.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from 'react';
+import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useResponsive } from '@actual-app/components/hooks/useResponsive';
@@ -36,9 +36,11 @@ export const HistoricalAutomation = ({
const months =
template.type === 'average' ? template.numMonths : template.lookBack;
const [rawMonths, setRawMonths] = useState(String(months));
- useEffect(() => {
+ const [prevMonths, setPrevMonths] = useState(months);
+ if (months !== prevMonths) {
+ setPrevMonths(months);
setRawMonths(String(months));
- }, [months]);
+ }
const commitMonths = () => {
const parsed = Math.max(1, Math.trunc(Number(rawMonths)) || 1);
diff --git a/packages/desktop-client/src/components/budget/goals/editor/LimitAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/LimitAutomation.tsx
index 6f9b2148db..1f70031e59 100644
--- a/packages/desktop-client/src/components/budget/goals/editor/LimitAutomation.tsx
+++ b/packages/desktop-client/src/components/budget/goals/editor/LimitAutomation.tsx
@@ -1,3 +1,4 @@
+import { useState } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { Select } from '@actual-app/components/select';
@@ -45,10 +46,10 @@ export const LimitAutomation = ({
template.amount,
format.currency.decimalPlaces,
);
- const start =
- template.start ??
- defaultWeeklyStart ??
- dayFromDate(firstDayOfMonth(new Date()));
+ const [currentMonthStart] = useState(() =>
+ dayFromDate(firstDayOfMonth(new Date())),
+ );
+ const start = template.start ?? defaultWeeklyStart ?? currentMonthStart;
const dayOfWeek = getDay(parseDate(start));
const hold = template.hold;
diff --git a/packages/desktop-client/src/components/budget/goals/editor/RemainderAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/RemainderAutomation.tsx
index 39a24fdbd7..d49f098f56 100644
--- a/packages/desktop-client/src/components/budget/goals/editor/RemainderAutomation.tsx
+++ b/packages/desktop-client/src/components/budget/goals/editor/RemainderAutomation.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from 'react';
+import { useState } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { Input } from '@actual-app/components/input';
@@ -25,9 +25,12 @@ export const RemainderAutomation = ({
// Track the raw input so the user can clear and retype without the field
// snapping back. Commit (and clamp) on blur.
const [rawWeight, setRawWeight] = useState(String(committedWeight));
- useEffect(() => {
+ const [prevCommittedWeight, setPrevCommittedWeight] =
+ useState(committedWeight);
+ if (committedWeight !== prevCommittedWeight) {
+ setPrevCommittedWeight(committedWeight);
setRawWeight(String(committedWeight));
- }, [committedWeight]);
+ }
const commitWeight = () => {
const parsed = Math.max(1, Math.trunc(Number(rawWeight)) || 1);
diff --git a/packages/desktop-client/src/components/common/AriaRouterProvider.tsx b/packages/desktop-client/src/components/common/AriaRouterProvider.tsx
index 58f3ae4445..4ae610f1ba 100644
--- a/packages/desktop-client/src/components/common/AriaRouterProvider.tsx
+++ b/packages/desktop-client/src/components/common/AriaRouterProvider.tsx
@@ -12,6 +12,7 @@ export function AriaRouterProvider({ children }: AriaRouterProviderProps) {
const navigate = useNavigate();
return (
+ // oxlint-disable-next-line react/hooks
<RouterProvider navigate={path => navigate(path)} useHref={useHref}>
{children}
</RouterProvider>
diff --git a/packages/desktop-client/src/components/common/Modal.tsx b/packages/desktop-client/src/components/common/Modal.tsx
index b0fd615a98..47e85d4927 100644
--- a/packages/desktop-client/src/components/common/Modal.tsx
+++ b/packages/desktop-client/src/components/common/Modal.tsx
@@ -304,7 +304,7 @@ const ModalContentContainer = ({
}: ModalContentContainerProps) => {
const contentRef = useRef<HTMLDivElement>(null);
const mounted = useRef(false);
- const rotateFactor = useRef(Math.random() * 10 - 5);
+ const [rotateFactor] = useState(() => Math.random() * 10 - 5);
useLayoutEffect(() => {
if (!contentRef.current) {
@@ -321,7 +321,7 @@ const ModalContentContainer = ({
contentRef.current.style.willChange = 'auto';
contentRef.current.style.pointerEvents = 'auto';
} else {
- contentRef.current.style.transform = `translateY(-40px) scale(.95) rotate(${rotateFactor.current}deg)`;
+ contentRef.current.style.transform = `translateY(-40px) scale(.95) rotate(${rotateFactor}deg)`;
contentRef.current.style.pointerEvents = 'none';
}
}
@@ -354,7 +354,7 @@ const ModalContentContainer = ({
} else {
setProps();
}
- }, [noAnimation, isActive]);
+ }, [noAnimation, isActive, rotateFactor]);
return (
<View
diff --git a/packages/desktop-client/src/components/filters/FiltersMenu.tsx b/packages/desktop-client/src/components/filters/FiltersMenu.tsx
index 5d79460251..176c46e3e0 100644
--- a/packages/desktop-client/src/components/filters/FiltersMenu.tsx
+++ b/packages/desktop-client/src/components/filters/FiltersMenu.tsx
@@ -66,6 +66,8 @@ type AmountInputRef = HTMLInputElement & {
let isDatepickerClick = false;
+const PARSE_REFERENCE_DATE = new Date(0);
+
const filterFields = [
'date',
'account',
@@ -137,7 +139,7 @@ function ConfigureField<T extends RuleConditionEntity>({
typeof value === 'string' &&
/^\d{4}-\d{2}$/.test(value)
) {
- const date = parseDate(value, 'yyyy-MM', new Date());
+ const date = parseDate(value, 'yyyy-MM', PARSE_REFERENCE_DATE);
if (isDateValid(date)) {
return formatDate(date, getMonthYearFormat(dateFormat));
}
diff --git a/packages/desktop-client/src/components/manager/BudgetFileSelection.tsx b/packages/desktop-client/src/components/manager/BudgetFileSelection.tsx
index 0bcf1c5e52..1d6ba7cc57 100644
--- a/packages/desktop-client/src/components/manager/BudgetFileSelection.tsx
+++ b/packages/desktop-client/src/components/manager/BudgetFileSelection.tsx
@@ -544,13 +544,14 @@ export function BudgetFileSelection({
const userData = useSelector(state => state.user.data);
const serverStatus = useSyncServerStatus();
+ const userId = userData?.userId;
const fetchUsers = useCallback(async () => {
try {
- setCurrentUserId(userData?.userId ?? '');
+ setCurrentUserId(userId ?? '');
} catch (error) {
console.error('Failed to fetch users:', error);
}
- }, [userData?.userId]);
+ }, [userId]);
useEffect(() => {
if (multiuserEnabled && !userData?.offline) {
diff --git a/packages/desktop-client/src/components/manager/ConfigServer.tsx b/packages/desktop-client/src/components/manager/ConfigServer.tsx
index d4ac1ed334..b4ee6ae073 100644
--- a/packages/desktop-client/src/components/manager/ConfigServer.tsx
+++ b/packages/desktop-client/src/components/manager/ConfigServer.tsx
@@ -286,12 +286,14 @@ export function ConfigServer() {
const navigate = useNavigate();
const location = useLocation();
const userData = useSelector(state => state.user.data);
- const [url, setUrl] = useState('');
const currentUrl = useServerURL();
const setServerUrl = useSetServerURL();
- useEffect(() => {
+ const [url, setUrl] = useState(currentUrl);
+ const [prevCurrentUrl, setPrevCurrentUrl] = useState(currentUrl);
+ if (currentUrl !== prevCurrentUrl) {
+ setPrevCurrentUrl(currentUrl);
setUrl(currentUrl);
- }, [currentUrl]);
+ }
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
diff --git a/packages/desktop-client/src/components/manager/subscribe/Login.tsx b/packages/desktop-client/src/components/manager/subscribe/Login.tsx
index d817266d3c..8bec1350dc 100644
--- a/packages/desktop-client/src/components/manager/subscribe/Login.tsx
+++ b/packages/desktop-client/src/components/manager/subscribe/Login.tsx
@@ -302,6 +302,12 @@ export function Login() {
const dispatch = useDispatch();
const defaultLoginMethod = useLoginMethod();
const [method, setMethod] = useState(defaultLoginMethod);
+ const [prevDefaultLoginMethod, setPrevDefaultLoginMethod] =
+ useState(defaultLoginMethod);
+ if (defaultLoginMethod !== prevDefaultLoginMethod) {
+ setPrevDefaultLoginMethod(defaultLoginMethod);
+ setMethod(defaultLoginMethod);
+ }
const [searchParams, _setSearchParams] = useSearchParams();
const [error, setError] = useState(null);
const { checked } = useBootstrapped();
@@ -309,10 +315,6 @@ export function Login() {
const loginMethodRef = useRef<HTMLButtonElement>(null);
const [loginMethodMenuOpen, setLoginMethodMenuOpen] = useState(false);
- useEffect(() => {
- setMethod(defaultLoginMethod);
- }, [defaultLoginMethod]);
-
useEffect(() => {
if (checked && !searchParams.has('error')) {
void (async () => {
diff --git a/packages/desktop-client/src/components/mobile/rules/MobileRuleEditPage.tsx b/packages/desktop-client/src/components/mobile/rules/MobileRuleEditPage.tsx
index 0dee6e8984..980729ce3f 100644
--- a/packages/desktop-client/src/components/mobile/rules/MobileRuleEditPage.tsx
+++ b/packages/desktop-client/src/components/mobile/rules/MobileRuleEditPage.tsx
@@ -32,15 +32,16 @@ export function MobileRuleEditPage() {
const [rule, setRule] = useState<RuleEntity | null>(null);
const [isLoading, setIsLoading] = useState(false);
+ const ruleId = rule?.id;
const { schedules = [] } = useSchedules({
query: useMemo(
() =>
- rule?.id
+ ruleId
? q('schedules')
- .filter({ rule: rule.id, completed: false })
+ .filter({ rule: ruleId, completed: false })
.select('*')
: q('schedules').filter({ id: null }).select('*'), // Return empty result when no rule
- [rule?.id],
+ [ruleId],
),
});
diff --git a/packages/desktop-client/src/components/mobile/transactions/FocusableAmountInput.tsx b/packages/desktop-client/src/components/mobile/transactions/FocusableAmountInput.tsx
index 100d3fdd3f..3aa0257e3f 100644
--- a/packages/desktop-client/src/components/mobile/transactions/FocusableAmountInput.tsx
+++ b/packages/desktop-client/src/components/mobile/transactions/FocusableAmountInput.tsx
@@ -196,6 +196,11 @@ export const FocusableAmountInput = memo(function FocusableAmountInput({
}: FocusableAmountInputProps) {
const [isNegative, setIsNegative] = useState(true);
const [liveValue, setLiveValue] = useState(Math.abs(value));
+ const [prevValue, setPrevValue] = useState(value);
+ if (value !== prevValue) {
+ setPrevValue(value);
+ setLiveValue(Math.abs(value));
+ }
const maybeApplyNegative = (amount: number, negative: boolean) => {
const absValue = Math.abs(amount);
@@ -211,10 +216,6 @@ export const FocusableAmountInput = memo(function FocusableAmountInput({
onChangeValue?.(text);
};
- useEffect(() => {
- setLiveValue(Math.abs(value));
- }, [value]);
-
useEffect(() => {
if (sign) {
setIsNegative(sign === '-');
diff --git a/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx b/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx
index 4bac7df428..7c2ba6b8e3 100644
--- a/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx
+++ b/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx
@@ -794,7 +794,7 @@ const TransactionEditInner = memo<TransactionEditInnerProps>(
onConfirmSave();
}
}
- }, [isAdding, dispatch, navigate, onSave, unserializedTransactions, t]);
+ }, [isAdding, dispatch, navigate, onSave, unserializedTransactions]);
const onSchedule = useCallback(async () => {
const [unserializedTransaction] = unserializedTransactions;
@@ -1189,7 +1189,12 @@ const TransactionEditInner = memo<TransactionEditInnerProps>(
transferAccount: getTransferAccount(transaction),
});
- const transactionDate = parseDate(transaction.date, dateFormat, new Date());
+ const [referenceDate] = useState(() => new Date());
+ const transactionDate = parseDate(
+ transaction.date,
+ dateFormat,
+ referenceDate,
+ );
const dateDefaultValue = monthUtils.dayFromDate(transactionDate);
const remaining = transaction.error?.difference ?? 0;
@@ -2077,12 +2082,7 @@ function TransactionEditUnconnected({
);
}
-type TransactionEditProps = Omit<
- TransactionEditUnconnectedProps,
- 'categories' | 'accounts' | 'payees' | 'lastTransaction' | 'dateFormat'
->;
-
-export const TransactionEdit = (props: TransactionEditProps) => {
+export const TransactionEdit = () => {
const { data: { list: categories } = { list: [] } } = useCategories();
const { data: payees = [] } = usePayees();
const lastTransaction = useSelector(
@@ -2094,7 +2094,6 @@ export const TransactionEdit = (props: TransactionEditProps) => {
return (
<SingleActiveEditFormProvider formName="mobile-transaction">
<TransactionEditUnconnected
- {...props}
categories={categories}
payees={payees}
lastTransaction={lastTransaction}
diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/useBudgetAutomationsEditor.ts b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/useBudgetAutomationsEditor.ts
index 2d7b0257c8..6218cdb7e5 100644
--- a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/useBudgetAutomationsEditor.ts
+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/useBudgetAutomationsEditor.ts
@@ -69,6 +69,7 @@ export function useBudgetAutomationsEditor({
onClose,
}: UseBudgetAutomationsEditorArgs) {
const dispatch = useDispatch();
+ const [today] = useState(() => new Date());
const { groups: cleanupGroups, createGroup: createCleanupGroup } =
useCleanupGroups();
@@ -215,7 +216,7 @@ export function useBudgetAutomationsEditor({
entry.displayType,
templates,
schedules,
- new Date(),
+ today,
validPercentageSources,
),
);
diff --git a/packages/desktop-client/src/components/modals/EnableBankingExternalMsgModal.tsx b/packages/desktop-client/src/components/modals/EnableBankingExternalMsgModal.tsx
index 50d152bfec..3a51882b08 100644
--- a/packages/desktop-client/src/components/modals/EnableBankingExternalMsgModal.tsx
+++ b/packages/desktop-client/src/components/modals/EnableBankingExternalMsgModal.tsx
@@ -125,7 +125,7 @@ export function EnableBankingExternalMsgModal({
const [language] = useGlobalPref('language');
const browserTimezone =
- Intl.DateTimeFormat().resolvedOptions().timeZone || '';
+ new Intl.DateTimeFormat().resolvedOptions().timeZone || '';
const browserLocale = language || navigator.language || 'en-US';
const detectedCountry = getCountryFromBrowser(
browserTimezone,
diff --git a/packages/desktop-client/src/components/modals/GoCardlessExternalMsgModal.test.tsx b/packages/desktop-client/src/components/modals/GoCardlessExternalMsgModal.test.tsx
index 1edaeb331d..6f2f95dd51 100644
--- a/packages/desktop-client/src/components/modals/GoCardlessExternalMsgModal.test.tsx
+++ b/packages/desktop-client/src/components/modals/GoCardlessExternalMsgModal.test.tsx
@@ -39,9 +39,9 @@ describe('GoCardlessExternalMsgModal - Country Auto-selection', () => {
// Mock timezone to Germany
global.Intl = {
...originalIntl,
- DateTimeFormat: vi.fn(() => ({
- resolvedOptions: () => ({ timeZone: 'Europe/Berlin' }),
- })) as unknown as typeof Intl.DateTimeFormat,
+ DateTimeFormat: vi.fn(function () {
+ return { resolvedOptions: () => ({ timeZone: 'Europe/Berlin' }) };
+ }) as unknown as typeof Intl.DateTimeFormat,
} as typeof Intl;
Object.defineProperty(global, 'navigator', {
@@ -64,9 +64,9 @@ describe('GoCardlessExternalMsgModal - Country Auto-selection', () => {
// Mock timezone to US (not supported)
global.Intl = {
...originalIntl,
- DateTimeFormat: vi.fn(() => ({
- resolvedOptions: () => ({ timeZone: 'America/New_York' }),
- })) as unknown as typeof Intl.DateTimeFormat,
+ DateTimeFormat: vi.fn(function () {
+ return { resolvedOptions: () => ({ timeZone: 'America/New_York' }) };
+ }) as unknown as typeof Intl.DateTimeFormat,
} as typeof Intl;
// But locale is UK
@@ -89,9 +89,9 @@ describe('GoCardlessExternalMsgModal - Country Auto-selection', () => {
// Mock timezone to US
global.Intl = {
...originalIntl,
- DateTimeFormat: vi.fn(() => ({
- resolvedOptions: () => ({ timeZone: 'America/New_York' }),
- })) as unknown as typeof Intl.DateTimeFormat,
+ DateTimeFormat: vi.fn(function () {
+ return { resolvedOptions: () => ({ timeZone: 'America/New_York' }) };
+ }) as unknown as typeof Intl.DateTimeFormat,
} as typeof Intl;
// Locale is also US
@@ -114,9 +114,9 @@ describe('GoCardlessExternalMsgModal - Country Auto-selection', () => {
// Mock timezone to France
global.Intl = {
...originalIntl,
- DateTimeFormat: vi.fn(() => ({
- resolvedOptions: () => ({ timeZone: 'Europe/Paris' }),
- })) as unknown as typeof Intl.DateTimeFormat,
+ DateTimeFormat: vi.fn(function () {
+ return { resolvedOptions: () => ({ timeZone: 'Europe/Paris' }) };
+ }) as unknown as typeof Intl.DateTimeFormat,
} as typeof Intl;
// Locale is German
diff --git a/packages/desktop-client/src/components/modals/GoCardlessExternalMsgModal.tsx b/packages/desktop-client/src/components/modals/GoCardlessExternalMsgModal.tsx
index 92402030b6..e28eac6535 100644
--- a/packages/desktop-client/src/components/modals/GoCardlessExternalMsgModal.tsx
+++ b/packages/desktop-client/src/components/modals/GoCardlessExternalMsgModal.tsx
@@ -97,7 +97,7 @@ export function GoCardlessExternalMsgModal({
const [language] = useGlobalPref('language');
const browserTimezone =
- Intl.DateTimeFormat().resolvedOptions().timeZone || '';
+ new Intl.DateTimeFormat().resolvedOptions().timeZone || '';
const browserLocale = language || navigator.language || 'en-US';
const detectedCountry = getCountryFromBrowser(
browserTimezone,
diff --git a/packages/desktop-client/src/components/modals/HoldBufferModal.tsx b/packages/desktop-client/src/components/modals/HoldBufferModal.tsx
index 815388b801..dd1f169d43 100644
--- a/packages/desktop-client/src/components/modals/HoldBufferModal.tsx
+++ b/packages/desktop-client/src/components/modals/HoldBufferModal.tsx
@@ -1,4 +1,4 @@
-import React, { useEffect, useState } from 'react';
+import React, { useState } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { Button } from '@actual-app/components/button';
@@ -23,11 +23,12 @@ export function HoldBufferModal({ onSubmit }: HoldBufferModalProps) {
const { t } = useTranslation(); // Initialize i18next
const [hideFraction] = useSyncedPref('hideFraction');
const available = useEnvelopeSheetValue(envelopeBudget.toBudget) ?? 0;
- const [amount, setAmount] = useState<number>(0);
-
- useEffect(() => {
+ const [amount, setAmount] = useState<number>(available);
+ const [prevAvailable, setPrevAvailable] = useState(available);
+ if (available !== prevAvailable) {
+ setPrevAvailable(available);
setAmount(available);
- }, [available]);
+ }
const _onSubmit = (newAmount: number) => {
if (newAmount) {
diff --git a/packages/desktop-client/src/components/reports/CategorySelector.tsx b/packages/desktop-client/src/components/reports/CategorySelector.tsx
index 8664c1ff2e..00af28b0ab 100644
--- a/packages/desktop-client/src/components/reports/CategorySelector.tsx
+++ b/packages/desktop-client/src/components/reports/CategorySelector.tsx
@@ -1,5 +1,5 @@
// @ts-strict-ignore
-import React, { Fragment, useMemo, useState } from 'react';
+import React, { Fragment, useState } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { Button } from '@actual-app/components/button';
@@ -50,10 +50,7 @@ export function CategorySelector({
selectedCategories = categoryGroups.flatMap(cg => cg.categories);
}
- const selectedCategoryMap = useMemo(
- () => selectedCategories.map(selected => selected.id),
- [selectedCategories],
- );
+ const selectedCategoryMap = selectedCategories.map(selected => selected.id);
const allCategoriesSelected = selectAll.every(category =>
selectedCategoryMap.includes(category.id),
diff --git a/packages/desktop-client/src/components/reports/graphs/CalendarGraph.tsx b/packages/desktop-client/src/components/reports/graphs/CalendarGraph.tsx
index b704066d4b..2558030e58 100644
--- a/packages/desktop-client/src/components/reports/graphs/CalendarGraph.tsx
+++ b/packages/desktop-client/src/components/reports/graphs/CalendarGraph.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from 'react';
+import { useState } from 'react';
import type { Ref } from 'react';
import { Trans } from 'react-i18next';
@@ -44,7 +44,7 @@ export function CalendarGraph({
}: CalendarGraphProps) {
const format = useFormat();
- const startingDate = startOfWeek(new Date(), {
+ const startingDate = startOfWeek(start, {
weekStartsOn:
firstDayOfWeekIdx !== undefined &&
!Number.isNaN(parseInt(firstDayOfWeekIdx)) &&
@@ -242,12 +242,6 @@ type DayButtonProps = {
onPress: () => void;
};
function DayButton({ day, onPress, fontSize, resizeRef }: DayButtonProps) {
- const [currentFontSize, setCurrentFontSize] = useState(fontSize);
-
- useEffect(() => {
- setCurrentFontSize(fontSize);
- }, [fontSize]);
-
return (
<Button
ref={resizeRef}
@@ -315,7 +309,7 @@ function DayButton({ day, onPress, fontSize, resizeRef }: DayButtonProps) {
/>
<span
style={{
- fontSize: `${currentFontSize}px`,
+ fontSize: `${fontSize}px`,
fontWeight: 500,
position: 'relative',
}}
diff --git a/packages/desktop-client/src/components/reports/graphs/NetWorthGraph.tsx b/packages/desktop-client/src/components/reports/graphs/NetWorthGraph.tsx
index 417cd44cba..3780eb2fb5 100644
--- a/packages/desktop-client/src/components/reports/graphs/NetWorthGraph.tsx
+++ b/packages/desktop-client/src/components/reports/graphs/NetWorthGraph.tsx
@@ -33,6 +33,8 @@ import { usePrivacyMode } from '#hooks/usePrivacyMode';
import { computePadding } from './util/computePadding';
+const PARSE_REFERENCE_DATE = new Date(0);
+
type NetWorthDataPoint = {
x: string;
y: number;
@@ -334,7 +336,7 @@ export function NetWorthGraph({
const pointFormat = getIntervalFormat(interval, dateFormat);
return graphData.data
.filter(point => {
- const date = parse(point.x, pointFormat, new Date());
+ const date = parse(point.x, pointFormat, PARSE_REFERENCE_DATE);
return getDay(date) === 1; // Monday
})
.map(point => point.x);
diff --git a/packages/desktop-client/src/components/reports/reports/Calendar.tsx b/packages/desktop-client/src/components/reports/reports/Calendar.tsx
index fe9e0a5c0c..6eeaa730d8 100644
--- a/packages/desktop-client/src/components/reports/reports/Calendar.tsx
+++ b/packages/desktop-client/src/components/reports/reports/Calendar.tsx
@@ -103,7 +103,8 @@ function CalendarInner({ widget, parameters }: CalendarInnerProps) {
const [end, setEnd] = useState(monthUtils.currentDay());
const [mode, setMode] = useState<TimeFrame['mode']>('full');
const [query, setQuery] = useState<Query | undefined>(undefined);
- const [dirty, setDirty] = useState(false);
+ const [refetchKey, setRefetchKey] = useState(0);
+ const [earliestTransaction, setEarliestTransaction] = useState('');
const [latestTransaction, setLatestTransaction] = useState('');
const {
@@ -173,19 +174,19 @@ function CalendarInner({ widget, parameters }: CalendarInnerProps) {
}
}, [widget?.meta?.conditions, onApplyFilter, parameters]);
- const params = useMemo(() => {
- if (dirty === true) {
- setDirty(false);
- }
-
- return calendarSpreadsheet(
- start,
- end,
- conditions,
- conditionsOp,
- firstDayOfWeekIdx,
- );
- }, [start, end, conditions, conditionsOp, firstDayOfWeekIdx, dirty]);
+ const report = useMemo(
+ () => ({
+ refetchKey,
+ getData: calendarSpreadsheet(
+ start,
+ end,
+ conditions,
+ conditionsOp,
+ firstDayOfWeekIdx,
+ ),
+ }),
+ [start, end, conditions, conditionsOp, firstDayOfWeekIdx, refetchKey],
+ );
const [sortField, setSortField] = useState('');
const [ascDesc, setAscDesc] = useState<'asc' | 'desc'>('desc');
@@ -238,7 +239,7 @@ function CalendarInner({ widget, parameters }: CalendarInnerProps) {
scrollbarContainer,
) as Ref<HTMLDivElement>;
- const data = useReport('calendar', params);
+ const data = useReport('calendar', report.getData);
const [allMonths, setAllMonths] = useState<
Array<{
@@ -429,6 +430,7 @@ function CalendarInner({ widget, parameters }: CalendarInnerProps) {
);
const refContainer = useRef<HTMLDivElement>(null);
+ const [totalHeight, setTotalHeight] = useState(0);
useEffect(() => {
if (refContainer.current) {
@@ -436,7 +438,6 @@ function CalendarInner({ widget, parameters }: CalendarInnerProps) {
}
}, [query]);
- const [totalHeight, setTotalHeight] = useState(0);
const closeY = useRef(3000);
const openY = 0;
@@ -515,8 +516,6 @@ function CalendarInner({ widget, parameters }: CalendarInnerProps) {
},
);
- const [earliestTransaction, setEarliestTransaction] = useState('');
-
return (
<Page
header={
@@ -682,7 +681,7 @@ function CalendarInner({ widget, parameters }: CalendarInnerProps) {
sortField={sortField}
ascDesc={ascDesc}
onChange={() => {}}
- onRefetch={() => setDirty(true)}
+ onRefetch={() => setRefetchKey(key => key + 1)}
onCloseAddTransaction={() => {}}
onCreatePayee={async () => null}
onApplyFilter={() => {}}
diff --git a/packages/desktop-client/src/components/reports/reports/CashFlow.tsx b/packages/desktop-client/src/components/reports/reports/CashFlow.tsx
index 7f8dab39da..67f428a19a 100644
--- a/packages/desktop-client/src/components/reports/reports/CashFlow.tsx
+++ b/packages/desktop-client/src/components/reports/reports/CashFlow.tsx
@@ -96,6 +96,7 @@ function CashFlowInner({ widget }: CashFlowInnerProps) {
const [showBalance, setShowBalance] = useState(
widget?.meta?.showBalance ?? true,
);
+ const [earliestTransaction, setEarliestTransaction] = useState('');
const [latestTransaction, setLatestTransaction] = useState('');
const [isConcise, setIsConcise] = useState(false);
@@ -241,7 +242,6 @@ function CashFlowInner({ widget }: CashFlowInnerProps) {
});
};
- const [earliestTransaction, setEarliestTransaction] = useState('');
const [_firstDayOfWeekIdx] = useSyncedPref('firstDayOfWeekIdx');
const firstDayOfWeekIdx = _firstDayOfWeekIdx || '0';
diff --git a/packages/desktop-client/src/components/reports/reports/NetWorth.tsx b/packages/desktop-client/src/components/reports/reports/NetWorth.tsx
index 462ce53976..d08e1980ff 100644
--- a/packages/desktop-client/src/components/reports/reports/NetWorth.tsx
+++ b/packages/desktop-client/src/components/reports/reports/NetWorth.tsx
@@ -120,6 +120,7 @@ function NetWorthInner({ widget }: NetWorthInnerProps) {
[widget?.meta?.interval, getDefaultIntervalForMode],
);
+ const [earliestTransaction, setEarliestTransaction] = useState('');
const [latestTransaction, setLatestTransaction] = useState('');
const [_firstDayOfWeekIdx] = useSyncedPref('firstDayOfWeekIdx');
@@ -286,8 +287,6 @@ function NetWorthInner({ widget }: NetWorthInnerProps) {
});
};
- const [earliestTransaction, setEarliestTransaction] = useState('');
-
if (!allMonths || !data) {
return null;
}
diff --git a/packages/desktop-client/src/components/settings/ThemeInstaller.tsx b/packages/desktop-client/src/components/settings/ThemeInstaller.tsx
index 8addfc30f4..8f2ea32687 100644
--- a/packages/desktop-client/src/components/settings/ThemeInstaller.tsx
+++ b/packages/desktop-client/src/components/settings/ThemeInstaller.tsx
@@ -1,4 +1,4 @@
-import React, { useCallback, useEffect, useState } from 'react';
+import React, { useCallback, useState } from 'react';
import { TextArea } from 'react-aria-components';
import { Trans, useTranslation } from 'react-i18next';
import { AutoSizer } from 'react-virtualized-auto-sizer';
@@ -55,7 +55,9 @@ export function ThemeInstaller({
const [selectedCatalogTheme, setSelectedCatalogTheme] =
useState<CatalogTheme | null>(null);
const [erroringTheme, setErroringTheme] = useState<CatalogTheme | null>(null);
- const [pastedCss, setPastedCss] = useState('');
+ // Mount-only: pref changes while the installer is open should not clobber
+ // in-progress edits to the textarea.
+ const [pastedCss, setPastedCss] = useState(customCssOverride || '');
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -66,15 +68,6 @@ export function ThemeInstaller({
error: catalogError,
} = useThemeCatalog();
- // Mount-only: pref changes while the installer is open should not clobber
- // in-progress edits to the textarea.
- useEffect(() => {
- if (customCssOverride) {
- setPastedCss(customCssOverride);
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
-
// Calculate theme item width based on container width (always 3 per row)
const getItemWidth = useCallback((containerWidth: number) => {
const availableWidth =
diff --git a/packages/desktop-client/src/components/settings/index.tsx b/packages/desktop-client/src/components/settings/index.tsx
index 0f707465c3..c12db86792 100644
--- a/packages/desktop-client/src/components/settings/index.tsx
+++ b/packages/desktop-client/src/components/settings/index.tsx
@@ -50,11 +50,11 @@ function About() {
const serverURL = useServerURL();
const version = useServerVersion();
const versionInfo = useSelector(state => state.app.versionInfo);
+ const dispatch = useDispatch();
const [notifyWhenUpdateIsAvailable, setNotifyWhenUpdateIsAvailablePref] =
useGlobalPref('notifyWhenUpdateIsAvailable', () => {
void dispatch(getLatestAppVersion());
});
- const dispatch = useDispatch();
const [showNewsFeed, setShowNewsFeedPref] = useGlobalPref('showNewsFeed');
const isNewsFeedEnabled = Boolean(showNewsFeed);
diff --git a/packages/desktop-client/src/components/table.tsx b/packages/desktop-client/src/components/table.tsx
index 29ec5f9538..21805c9fef 100644
--- a/packages/desktop-client/src/components/table.tsx
+++ b/packages/desktop-client/src/components/table.tsx
@@ -1047,6 +1047,15 @@ export const Table = forwardRef(
},
}));
+ function saveScrollDelayed() {
+ saveScrollWidth(
+ scrollContainer.current?.offsetParent
+ ? scrollContainer.current?.offsetParent.clientWidth
+ : 0,
+ scrollContainer.current ? scrollContainer.current.clientWidth : 0,
+ );
+ }
+
useLayoutEffect(() => {
// We wait for the list to mount because AutoSizer needs to run
// before it's mounted
@@ -1064,15 +1073,6 @@ export const Table = forwardRef(
}
});
- function saveScrollDelayed() {
- saveScrollWidth(
- scrollContainer.current?.offsetParent
- ? scrollContainer.current?.offsetParent.clientWidth
- : 0,
- scrollContainer.current ? scrollContainer.current.clientWidth : 0,
- );
- }
-
function renderRow({ index, style, key }) {
const item = items[index];
const editing = editingId === item.id;
diff --git a/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx b/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx
index 67fd812a25..448ebf26b2 100644
--- a/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx
+++ b/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx
@@ -1027,7 +1027,7 @@ describe('Transactions', () => {
expect(getTransactions()[3].payee).toBe(null);
});
- test('dropdown escape resets the value ', async () => {
+ test('dropdown escape resets the value', async () => {
const { container } = renderTransactions();
const input = await editField(container, 'category', 2);
diff --git a/packages/desktop-client/src/components/transactions/TransactionsTable.tsx b/packages/desktop-client/src/components/transactions/TransactionsTable.tsx
index c8b90e57af..fa8d81a1dd 100644
--- a/packages/desktop-client/src/components/transactions/TransactionsTable.tsx
+++ b/packages/desktop-client/src/components/transactions/TransactionsTable.tsx
@@ -3232,7 +3232,7 @@ export const TransactionTable = forwardRef(
prevSplitsExpanded.current = splitsExpanded;
return result;
- }, [props.transactions, splitsExpanded]);
+ }, [prevSplitsExpanded, props.transactions, splitsExpanded]);
const transactionMap = useMemo(() => {
return new Map(
@@ -3648,14 +3648,14 @@ export const TransactionTable = forwardRef(
}
}
- const onScheduleTemporary = useCallback(() => {
+ const onScheduleTemporary = () => {
afterSave(() => {
shouldSchedule.current = true;
forceRerender({});
});
- }, []);
+ };
- const onAddTemporary = useCallback(() => {
+ const onAddTemporary = () => {
afterSave(() => {
shouldAdd.current = true;
// A little hacky - this forces a rerender which will cause the
@@ -3663,14 +3663,14 @@ export const TransactionTable = forwardRef(
// committed (the input could still be saving a value).
forceRerender({});
});
- }, []);
+ };
- const onAddAndCloseTemporary = useCallback(() => {
+ const onAddAndCloseTemporary = () => {
afterSave(() => {
shouldAddAndClose.current = true;
forceRerender({});
});
- }, []);
+ };
const {
onSave: onSaveProp,
@@ -3730,23 +3730,26 @@ export const TransactionTable = forwardRef(
onSaveProp(groupedTransaction);
}
},
- [onSaveProp, onApplyRulesProp],
+ [latestState, onSaveProp, onApplyRulesProp],
);
- const onDelete = useCallback((id: TransactionEntity['id']) => {
- const temporary = isTemporaryId(id);
+ const onDelete = useCallback(
+ (id: TransactionEntity['id']) => {
+ const temporary = isTemporaryId(id);
- if (temporary) {
- const newTrans = latestState.current.newTransactions;
+ if (temporary) {
+ const newTrans = latestState.current.newTransactions;
- if (id === newTrans[0].id) {
- // You can never delete the parent new transaction
- return;
- }
+ if (id === newTrans[0].id) {
+ // You can never delete the parent new transaction
+ return;
+ }
- setNewTransactions(deleteTransaction(newTrans, id).data);
- }
- }, []);
+ setNewTransactions(deleteTransaction(newTrans, id).data);
+ }
+ },
+ [latestState],
+ );
const onBatchDelete = useCallback(
(ids: TransactionEntity['id'][]) => {
@@ -3839,7 +3842,7 @@ export const TransactionTable = forwardRef(
}
}
};
- }, [onSplitProp, splitsExpandedDispatch]);
+ }, [latestState, onSplitProp, splitsExpandedDispatch]);
const { onAddSplit: onAddSplitProp } = props;
@@ -3866,7 +3869,7 @@ export const TransactionTable = forwardRef(
);
}
},
- [onAddSplitProp],
+ [latestState, onAddSplitProp],
);
const onDistributeRemainder = useCallback(
@@ -3996,7 +3999,7 @@ export const TransactionTable = forwardRef(
}
}
},
- [onSave],
+ [latestState, onSave],
);
function onCloseAddTransaction() {
diff --git a/packages/desktop-client/src/hooks/useQuery.ts b/packages/desktop-client/src/hooks/useQuery.ts
index beebe597bf..127ff5dd41 100644
--- a/packages/desktop-client/src/hooks/useQuery.ts
+++ b/packages/desktop-client/src/hooks/useQuery.ts
@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useState } from 'react';
+import { useEffect, useState } from 'react';
import type { DependencyList } from 'react';
import type { Query } from '@actual-app/core/shared/query';
@@ -18,8 +18,15 @@ export function useQuery<Response = unknown>(
): UseQueryResult<Response> {
// Memo the resulting query. We don't care if the function
// that creates the query changes, only the resulting query.
- // oxlint-disable-next-line react-hooks/exhaustive-deps -- caller owns deps
- const query = useMemo(makeQuery, dependencies);
+ const [memoizedQuery, setMemoizedQuery] = useState(() => ({
+ dependencies,
+ query: makeQuery(),
+ }));
+ let query = memoizedQuery.query;
+ if (!areDependenciesEqual(memoizedQuery.dependencies, dependencies)) {
+ query = makeQuery();
+ setMemoizedQuery({ dependencies, query });
+ }
const [data, setData] = useState<ReadonlyArray<Response> | null>(null);
const [isLoading, setIsLoading] = useState(true);
@@ -57,3 +64,10 @@ export function useQuery<Response = unknown>(
...(error && { error }),
};
}
+
+function areDependenciesEqual(a: DependencyList, b: DependencyList) {
+ return (
+ a.length === b.length &&
+ a.every((value, index) => Object.is(value, b[index]))
+ );
+}
diff --git a/packages/desktop-client/src/hooks/useRefEventListener.ts b/packages/desktop-client/src/hooks/useRefEventListener.ts
index b7bfa79183..5d813fa824 100644
--- a/packages/desktop-client/src/hooks/useRefEventListener.ts
+++ b/packages/desktop-client/src/hooks/useRefEventListener.ts
@@ -1,4 +1,4 @@
-import { useEffect, useRef, useState } from 'react';
+import { useEffect, useRef } from 'react';
import type { RefObject } from 'react';
export function useRefEventListener<
@@ -18,17 +18,26 @@ export function useRefEventListener<
callbackRef.current = callback;
// Mutating `ref.current` doesn't re-run effects, so the element can't go in
- // a dependency array. Re-resolve it after every render and mirror it into
- // state; `setTarget` bails out when the element hasn't moved.
- const [target, setTarget] = useState<EventTarget | null>(null);
- // oxlint-disable-next-line react-hooks/exhaustive-deps -- must run every render; the bail-out stops the update chain
- useEffect(() => {
- setTarget(
- ref instanceof Document || ref instanceof Window ? ref : ref.current,
- );
- });
+ // a dependency array. Re-resolve it after every render and only rebind the
+ // native listener when the element or `event` has actually changed.
+ const bindingRef = useRef<{
+ target: EventTarget;
+ event: EventType;
+ listener: EventListener;
+ } | null>(null);
useEffect(() => {
+ const target =
+ ref instanceof Document || ref instanceof Window ? ref : ref.current;
+ const binding = bindingRef.current;
+ if (binding && binding.target === target && binding.event === event) {
+ return;
+ }
+
+ if (binding) {
+ binding.target.removeEventListener(binding.event, binding.listener);
+ bindingRef.current = null;
+ }
if (!target) return;
const listener: EventListener = e =>
@@ -37,8 +46,16 @@ export function useRefEventListener<
e as HTMLElementEventMap[EventType],
);
target.addEventListener(event, listener);
+ bindingRef.current = { target, event, listener };
+ });
+
+ useEffect(() => {
return () => {
- target.removeEventListener(event, listener);
+ const binding = bindingRef.current;
+ if (binding) {
+ binding.target.removeEventListener(binding.event, binding.listener);
+ bindingRef.current = null;
+ }
};
- }, [target, event]);
+ }, []);
}
diff --git a/packages/desktop-client/src/hooks/useScrollListener.tsx b/packages/desktop-client/src/hooks/useScrollListener.tsx
index 5831eab64d..410adffbf0 100644
--- a/packages/desktop-client/src/hooks/useScrollListener.tsx
+++ b/packages/desktop-client/src/hooks/useScrollListener.tsx
@@ -158,7 +158,7 @@ export function ScrollProvider<T extends Element>({
}
}
}, delayMs),
- [delayMs, hasScrolledToEnd, isScrolling],
+ [delayMs, hasScrolledToEnd, isScrolling, listeners],
);
useEffect(() => {
@@ -191,7 +191,7 @@ export function ScrollProvider<T extends Element>({
listeners.current = listeners.current.filter(l => l !== listener);
};
},
- [],
+ [listeners],
);
return (
diff --git a/packages/desktop-client/src/hooks/useTransactionsSearch.ts b/packages/desktop-client/src/hooks/useTransactionsSearch.ts
index cc86331344..ab207b070e 100644
--- a/packages/desktop-client/src/hooks/useTransactionsSearch.ts
+++ b/packages/desktop-client/src/hooks/useTransactionsSearch.ts
@@ -44,7 +44,7 @@ export function useTransactionsSearch({
setIsSearching(true);
}
}, delayMs),
- [dateFormat, delayMs],
+ [dateFormat, delayMs, resetQueryRef, updateQueryRef],
);
useEffect(() => {
diff --git a/packages/loot-core/src/server/migrate/additive-migrations.test.ts b/packages/loot-core/src/server/migrate/additive-migrations.test.ts
index 7aa56c4ce3..4ebfa40b0a 100644
--- a/packages/loot-core/src/server/migrate/additive-migrations.test.ts
+++ b/packages/loot-core/src/server/migrate/additive-migrations.test.ts
@@ -9,6 +9,7 @@ import * as sqlite from '#platform/server/sqlite';
import {
ADDITIVE_ONLY_CUTOFF,
applyMigration,
+ getAppliedMigrations,
getMigrationId,
getMigrationList,
migrate,
@@ -115,6 +116,9 @@ describe('migrations are additive-only', () => {
ADDITIVE_ONLY_CUTOFF + 1,
]);
await migrate(db);
+ expect(await getAppliedMigrations(db)).toContain(
+ ADDITIVE_ONLY_CUTOFF + 1,
+ );
});
sqlite.closeDatabase(db);
});
diff --git a/packages/loot-core/src/server/migrate/migrations.test.ts b/packages/loot-core/src/server/migrate/migrations.test.ts
index 04cef9619d..8edd1820a9 100644
--- a/packages/loot-core/src/server/migrate/migrations.test.ts
+++ b/packages/loot-core/src/server/migrate/migrations.test.ts
@@ -7,6 +7,7 @@ import * as db from '#server/db';
import {
getAppliedMigrations,
+ getMigrationId,
getMigrationList,
getPending,
migrate,
@@ -28,20 +29,17 @@ describe('Migrations', () => {
});
test('applied migrations are returned in order', async () => {
- return withMigrationsDir(
- __dirname + '/../../mocks/migrations',
- async () => {
- await migrate(db.getDatabase());
+ const migrationsDir = __dirname + '/../../mocks/migrations';
+ return withMigrationsDir(migrationsDir, async () => {
+ await migrate(db.getDatabase());
- const migrations = await getAppliedMigrations(db.getDatabase());
- const last = 0;
- for (const migration of migrations) {
- if (migration <= last) {
- throw new Error('Found older migration out of order');
- }
- }
- },
- );
+ const migrations = await getAppliedMigrations(db.getDatabase());
+ const expected = (await getMigrationList(migrationsDir)).map(
+ getMigrationId,
+ );
+ expect(expected.length).toBeGreaterThan(0);
+ expect(migrations).toEqual(expected);
+ });
});
test('checks if there are unknown migrations', async () => {
diff --git a/packages/loot-core/src/server/transactions/transaction-rules.test.ts b/packages/loot-core/src/server/transactions/transaction-rules.test.ts
index 4701f944aa..2dea681e36 100644
--- a/packages/loot-core/src/server/transactions/transaction-rules.test.ts
+++ b/packages/loot-core/src/server/transactions/transaction-rules.test.ts
@@ -1062,7 +1062,7 @@ describe('Learning categories', () => {
expect(rule.actions[0].value).toBe(category);
}
- async function insertTransaction(
+ async function expectRuleAfterInsert(
transaction,
expectedCategory,
expectedRuleCount = 1,
@@ -1126,7 +1126,7 @@ describe('Learning categories', () => {
test('creates rule when inserting transactions', async () => {
await loadData();
- await insertTransaction(
+ await expectRuleAfterInsert(
{
id: 'one',
date: '2016-12-01',
@@ -1138,7 +1138,7 @@ describe('Learning categories', () => {
0,
);
- await insertTransaction(
+ await expectRuleAfterInsert(
{
id: 'two',
date: '2016-12-01',
@@ -1150,7 +1150,7 @@ describe('Learning categories', () => {
0,
);
- await insertTransaction(
+ await expectRuleAfterInsert(
{
id: 'three',
date: '2016-12-01',
@@ -1165,7 +1165,7 @@ describe('Learning categories', () => {
test('leaves existing rule alone if probable category is ambiguous', async () => {
await loadData();
- await insertTransaction(
+ await expectRuleAfterInsert(
{
id: 'one',
date: '2016-12-01',
@@ -1177,7 +1177,7 @@ describe('Learning categories', () => {
0,
);
- await insertTransaction(
+ await expectRuleAfterInsert(
{
id: 'two',
date: '2016-12-01',
@@ -1189,7 +1189,7 @@ describe('Learning categories', () => {
0,
);
- await insertTransaction(
+ await expectRuleAfterInsert(
{
id: 'three',
date: '2016-12-01',
@@ -1210,7 +1210,7 @@ describe('Learning categories', () => {
// Even though the system couldn't figure out the category to set,
// it should leave the existing rule alone
- await insertTransaction(
+ await expectRuleAfterInsert(
{
id: 'four',
date: '2016-12-01',
@@ -1233,7 +1233,7 @@ describe('Learning categories', () => {
actions: [{ op: 'set', field: 'category', value: 'beer' }],
});
- await insertTransaction(
+ await expectRuleAfterInsert(
{
id: 'one',
date: '2016-12-01',
@@ -1244,7 +1244,7 @@ describe('Learning categories', () => {
'beer',
1,
);
- await insertTransaction(
+ await expectRuleAfterInsert(
{
id: 'two',
date: '2016-12-01',
@@ -1255,7 +1255,7 @@ describe('Learning categories', () => {
'beer',
1,
);
- await insertTransaction(
+ await expectRuleAfterInsert(
{
id: 'three',
date: '2016-12-01',
@@ -1279,7 +1279,7 @@ describe('Learning categories', () => {
});
// Use a new payee, so the category should be remembered
- await insertTransaction(
+ await expectRuleAfterInsert(
{
id: 'three',
date: '2016-12-03',
@@ -1290,7 +1290,7 @@ describe('Learning categories', () => {
'beer',
1,
);
- await insertTransaction(
+ await expectRuleAfterInsert(
{
id: 'four',
date: '2016-12-03',
@@ -1301,7 +1301,7 @@ describe('Learning categories', () => {
'beer',
1,
);
- await insertTransaction(
+ await expectRuleAfterInsert(
{
id: 'five',
date: '2016-12-03',
diff --git a/packages/loot-core/src/shared/async.test.ts b/packages/loot-core/src/shared/async.test.ts
index 1fbe5fe6f5..d963975072 100644
--- a/packages/loot-core/src/shared/async.test.ts
+++ b/packages/loot-core/src/shared/async.test.ts
@@ -81,18 +81,19 @@ describe('async', () => {
const data = [];
const fn = sequential(makeFunction(data));
- void fn(1).then(() => {
+ const first = fn(1).then(() => {
// The next call should already have started (so it should have
// already appended 2 to the end). It shouldn't depend on this
// promise chain at all (important part being that if any errors
// happened in here, it wouldn't effect anything else)
expect(data).toEqual([1, 1, 1, 2]);
});
- fn(2, { throwError: true }).catch(() => {
+ const second = fn(2, { throwError: true }).catch(() => {
// Same as above
expect(data).toEqual([1, 1, 1, 2, 3]);
});
await fn(3);
+ await Promise.all([first, second]);
expect(data).toEqual([1, 1, 1, 2, 3, 3, 3]);
});
diff --git a/packages/loot-core/src/types/util.ts b/packages/loot-core/src/types/util.ts
index 3f7f83b764..48c0e4a3a4 100644
--- a/packages/loot-core/src/types/util.ts
+++ b/packages/loot-core/src/types/util.ts
@@ -1,5 +1,3 @@
-export type EmptyObject = Record<never, never>;
-
export type StripNever<T> = {
[K in keyof T as T[K] extends never ? never : K]: T[K];
};
diff --git a/upcoming-release-notes/enable-react-compiler-lint-rules.md b/upcoming-release-notes/enable-react-compiler-lint-rules.md
new file mode 100644
index 0000000000..14414d5a2e
--- /dev/null
+++ b/upcoming-release-notes/enable-react-compiler-lint-rules.md
@@ -0,0 +1,6 @@
+---
+category: Maintenance
+authors: [matt-fidd]
+---
+
+Enable React Compiler and Vitest lint rules