Skip to content

A local-first personal finance app

More typing improvements for Redux-related code (#1404)

Jed Fox9ef5fd12e06c
diff --git a/packages/desktop-client/src/components/App.js b/packages/desktop-client/src/components/App.js
index a544f76fc4..4befb0ffeb 100644
--- a/packages/desktop-client/src/components/App.js
+++ b/packages/desktop-client/src/components/App.js
@@ -1,14 +1,14 @@
import React, { Component } from 'react';
-import { connect } from 'react-redux';
+import { useSelector } from 'react-redux';
import { css } from 'glamor';
-import * as actions from 'loot-core/src/client/actions';
import {
init as initConnection,
send,
} from 'loot-core/src/platform/client/fetch';
+import { useActions } from '../hooks/useActions';
import installPolyfills from '../polyfills';
import { ResponsiveProvider } from '../ResponsiveProvider';
import { styles, hasHiddenScrollbars, ThemeStyle } from '../style';
@@ -139,11 +139,24 @@ class App extends Component {
}
}
-export default connect(
- state => ({
- budgetId: state.prefs.local && state.prefs.local.id,
- cloudFileId: state.prefs.local && state.prefs.local.cloudFileId,
- loadingText: state.app.loadingText,
- }),
- actions,
-)(App);
+export default function AppWrapper() {
+ let budgetId = useSelector(
+ state => state.prefs.local && state.prefs.local.id,
+ );
+ let cloudFileId = useSelector(
+ state => state.prefs.local && state.prefs.local.cloudFileId,
+ );
+ let loadingText = useSelector(state => state.app.loadingText);
+ let { loadBudget, closeBudget, loadGlobalPrefs } = useActions();
+
+ return (
+ <App
+ budgetId={budgetId}
+ cloudFileId={cloudFileId}
+ loadingText={loadingText}
+ loadBudget={loadBudget}
+ closeBudget={closeBudget}
+ loadGlobalPrefs={loadGlobalPrefs}
+ />
+ );
+}
diff --git a/packages/desktop-client/src/components/BankSyncStatus.js b/packages/desktop-client/src/components/BankSyncStatus.js
index 36c8d25af8..9cbe32bee7 100644
--- a/packages/desktop-client/src/components/BankSyncStatus.js
+++ b/packages/desktop-client/src/components/BankSyncStatus.js
@@ -1,15 +1,15 @@
import React from 'react';
-import { connect } from 'react-redux';
+import { useSelector } from 'react-redux';
import { useTransition, animated } from 'react-spring';
-import * as actions from 'loot-core/src/client/actions';
-
import { colors, styles } from '../style';
import AnimatedRefresh from './AnimatedRefresh';
import { View, Text } from './common';
-function BankSyncStatus({ accountsSyncing }) {
+export default function BankSyncStatus() {
+ let accountsSyncing = useSelector(state => state.account.accountsSyncing);
+
let name = accountsSyncing
? accountsSyncing === '__all'
? 'accounts'
@@ -62,10 +62,3 @@ function BankSyncStatus({ accountsSyncing }) {
</View>
);
}
-
-export default connect(
- state => ({
- accountsSyncing: state.account.accountsSyncing,
- }),
- actions,
-)(BankSyncStatus);
diff --git a/packages/desktop-client/src/components/FinancesApp.tsx b/packages/desktop-client/src/components/FinancesApp.tsx
index b85bce50cc..305281fa2c 100644
--- a/packages/desktop-client/src/components/FinancesApp.tsx
+++ b/packages/desktop-client/src/components/FinancesApp.tsx
@@ -1,7 +1,6 @@
import React, { type ReactElement, useEffect, useMemo } from 'react';
import { DndProvider } from 'react-dnd';
import { HTML5Backend as Backend } from 'react-dnd-html5-backend';
-import { connect } from 'react-redux';
import {
Route,
Routes,
@@ -15,13 +14,13 @@ import {
import hotkeys from 'hotkeys-js';
-import * as actions from 'loot-core/src/client/actions';
import { AccountsProvider } from 'loot-core/src/client/data-hooks/accounts';
import { PayeesProvider } from 'loot-core/src/client/data-hooks/payees';
import { SpreadsheetProvider } from 'loot-core/src/client/SpreadsheetProvider';
import checkForUpdateNotification from 'loot-core/src/client/update-notification';
import * as undo from 'loot-core/src/platform/client/undo';
+import { useActions } from '../hooks/useActions';
import Cog from '../icons/v1/Cog';
import PiggyBank from '../icons/v1/PiggyBank';
import Wallet from '../icons/v1/Wallet';
@@ -223,7 +222,8 @@ function RouterBehaviors({ getAccounts }) {
return null;
}
-function FinancesApp(props) {
+function FinancesApp() {
+ let actions = useActions();
useEffect(() => {
// The default key handler scope
hotkeys.setScope('app');
@@ -231,21 +231,21 @@ function FinancesApp(props) {
// Wait a little bit to make sure the sync button will get the
// sync start event. This can be improved later.
setTimeout(async () => {
- await props.sync();
+ await actions.sync();
await checkForUpdateNotification(
- props.addNotification,
+ actions.addNotification,
getIsOutdated,
getLatestVersion,
- props.loadPrefs,
- props.savePrefs,
+ actions.loadPrefs,
+ actions.savePrefs,
);
}, 100);
}, []);
return (
<BrowserRouter>
- <RouterBehaviors getAccounts={props.getAccounts} />
+ <RouterBehaviors getAccounts={actions.getAccounts} />
<ExposeNavigate />
<View style={{ height: '100%' }}>
@@ -302,8 +302,8 @@ function FinancesApp(props) {
);
}
-function FinancesAppWithContext(props) {
- let app = useMemo(() => <FinancesApp {...props} />, [props]);
+export default function FinancesAppWithContext() {
+ let app = useMemo(() => <FinancesApp />, []);
return (
<SpreadsheetProvider>
@@ -321,5 +321,3 @@ function FinancesAppWithContext(props) {
</SpreadsheetProvider>
);
}
-
-export default connect(null, actions)(FinancesAppWithContext);
diff --git a/packages/desktop-client/src/components/FloatableSidebar.js b/packages/desktop-client/src/components/FloatableSidebar.js
index bdc9583c50..d329d8b94e 100644
--- a/packages/desktop-client/src/components/FloatableSidebar.js
+++ b/packages/desktop-client/src/components/FloatableSidebar.js
@@ -1,7 +1,5 @@
import React, { createContext, useState, useContext, useMemo } from 'react';
-import { connect, useSelector } from 'react-redux';
-
-import * as actions from 'loot-core/src/client/actions';
+import { useSelector } from 'react-redux';
import { useResponsive } from '../ResponsiveProvider';
@@ -39,7 +37,11 @@ export function useSidebar() {
);
}
-function Sidebar({ floatingSidebar }) {
+export default function Sidebar() {
+ let floatingSidebar = useSelector(
+ state => state.prefs.global.floatingSidebar,
+ );
+
let sidebar = useSidebar();
let { isNarrowWidth } = useResponsive();
@@ -82,8 +84,3 @@ function Sidebar({ floatingSidebar }) {
</View>
);
}
-
-export default connect(
- state => ({ floatingSidebar: state.prefs.global.floatingSidebar }),
- actions,
-)(Sidebar);
diff --git a/packages/desktop-client/src/components/LoggedInUser.js b/packages/desktop-client/src/components/LoggedInUser.js
index a96d43fe5f..558c291746 100644
--- a/packages/desktop-client/src/components/LoggedInUser.js
+++ b/packages/desktop-client/src/components/LoggedInUser.js
@@ -1,22 +1,15 @@
import React, { useState, useEffect } from 'react';
-import { connect } from 'react-redux';
-
-import * as actions from 'loot-core/src/client/actions';
+import { useSelector } from 'react-redux';
+import { useActions } from '../hooks/useActions';
import { colors, styles } from '../style';
import { View, Text, Button, Tooltip, Menu } from './common';
import { useServerURL } from './ServerContext';
-function LoggedInUser({
- hideIfNoServer,
- userData,
- getUserData,
- signOut,
- closeBudget,
- style,
- color,
-}) {
+export default function LoggedInUser({ hideIfNoServer, style, color }) {
+ let userData = useSelector(state => state.userData);
+ let { getUserData, signOut, closeBudget } = useActions();
let [loading, setLoading] = useState(true);
let [menuOpen, setMenuOpen] = useState(false);
const serverUrl = useServerURL();
@@ -117,8 +110,3 @@ function LoggedInUser({
</View>
);
}
-
-export default connect(
- state => ({ userData: state.user.data }),
- actions,
-)(LoggedInUser);
diff --git a/packages/desktop-client/src/components/Modals.tsx b/packages/desktop-client/src/components/Modals.tsx
index ca5b47a990..f37aa10437 100644
--- a/packages/desktop-client/src/components/Modals.tsx
+++ b/packages/desktop-client/src/components/Modals.tsx
@@ -204,7 +204,6 @@ export default function Modals() {
<EditField
key={name}
modalProps={modalProps}
- actions={actions}
name={options.name}
onSubmit={options.onSubmit}
/>
diff --git a/packages/desktop-client/src/components/SidebarWithData.js b/packages/desktop-client/src/components/SidebarWithData.js
index 5a3fb6ca43..db6302c25f 100644
--- a/packages/desktop-client/src/components/SidebarWithData.js
+++ b/packages/desktop-client/src/components/SidebarWithData.js
@@ -1,15 +1,13 @@
import React, { useState, useEffect } from 'react';
-import { connect, useDispatch } from 'react-redux';
+import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router';
-import { bindActionCreators } from 'redux';
-
-import * as actions from 'loot-core/src/client/actions';
import { closeBudget } from 'loot-core/src/client/actions/budgets';
import * as Platform from 'loot-core/src/client/platform';
import * as queries from 'loot-core/src/client/queries';
import { send } from 'loot-core/src/platform/client/fetch';
+import { useActions } from '../hooks/useActions';
import ExpandArrow from '../icons/v0/ExpandArrow';
import { styles, colors } from '../style';
@@ -103,17 +101,17 @@ function EditableBudgetName({ prefs, savePrefs }) {
}
}
-function SidebarWithData({
- accounts,
- failedAccounts,
- updatedAccounts,
- replaceModal,
- prefs,
- floatingSidebar,
- savePrefs,
- saveGlobalPrefs,
- getAccounts,
-}) {
+export default function SidebarWithData() {
+ let accounts = useSelector(state => state.queries.accounts);
+ let failedAccounts = useSelector(state => state.account.failedAccounts);
+ let updatedAccounts = useSelector(state => state.queries.updatedAccounts);
+ let prefs = useSelector(state => state.prefs.local);
+ let floatingSidebar = useSelector(
+ state => state.prefs.global.floatingSidebar,
+ );
+
+ let { getAccounts, replaceModal, savePrefs, saveGlobalPrefs } = useActions();
+
useEffect(() => void getAccounts(), [getAccounts]);
async function onReorder(id, dropPos, targetId) {
@@ -150,14 +148,3 @@ function SidebarWithData({
/>
);
}
-
-export default connect(
- state => ({
- accounts: state.queries.accounts,
- failedAccounts: state.account.failedAccounts,
- updatedAccounts: state.queries.updatedAccounts,
- prefs: state.prefs.local,
- floatingSidebar: state.prefs.global.floatingSidebar,
- }),
- dispatch => bindActionCreators(actions, dispatch),
-)(SidebarWithData);
diff --git a/packages/desktop-client/src/components/Titlebar.js b/packages/desktop-client/src/components/Titlebar.js
index ed4567b064..6b825577bd 100644
--- a/packages/desktop-client/src/components/Titlebar.js
+++ b/packages/desktop-client/src/components/Titlebar.js
@@ -5,16 +5,16 @@ import React, {
useRef,
useContext,
} from 'react';
-import { connect } from 'react-redux';
+import { useSelector } from 'react-redux';
import { Routes, Route, useLocation, useNavigate } from 'react-router-dom';
import { css, media } from 'glamor';
-import * as actions from 'loot-core/src/client/actions';
import * as Platform from 'loot-core/src/client/platform';
import * as queries from 'loot-core/src/client/queries';
import { listen } from 'loot-core/src/platform/client/fetch';
+import { useActions } from '../hooks/useActions';
import useFeatureFlag from '../hooks/useFeatureFlag';
import ArrowLeft from '../icons/v1/ArrowLeft';
import AlertTriangle from '../icons/v2/AlertTriangle';
@@ -82,19 +82,19 @@ function UncategorizedButton() {
);
}
-function PrivacyButton({ localPrefs, onTogglePrivacy }) {
- let [isPrivacyEnabled, setIsPrivacyEnabled] = useState(
- localPrefs.isPrivacyEnabled,
+function PrivacyButton() {
+ let isPrivacyEnabled = useSelector(
+ state => state.prefs.local.isPrivacyEnabled,
);
- let togglePrivacy = () => {
- setIsPrivacyEnabled(!isPrivacyEnabled);
- onTogglePrivacy(!isPrivacyEnabled);
- };
+ let { savePrefs } = useActions();
let privacyIconStyle = { width: 23, height: 23 };
return (
- <Button type="bare" onClick={togglePrivacy}>
+ <Button
+ type="bare"
+ onClick={() => savePrefs({ isPrivacyEnabled: !isPrivacyEnabled })}
+ >
{isPrivacyEnabled ? (
<SvgEyeSlashed style={privacyIconStyle} />
) : (
@@ -104,7 +104,10 @@ function PrivacyButton({ localPrefs, onTogglePrivacy }) {
);
}
-export function SyncButton({ localPrefs, style, onSync }) {
+export function SyncButton({ style }) {
+ let cloudFileId = useSelector(state => state.prefs.local.cloudFileId);
+ let { sync } = useActions();
+
let [syncing, setSyncing] = useState(false);
let [syncState, setSyncState] = useState(null);
@@ -128,7 +131,7 @@ export function SyncButton({ localPrefs, style, onSync }) {
// file.
if (subtype === 'network') {
setSyncState('offline');
- } else if (!localPrefs.cloudFileId) {
+ } else if (!cloudFileId) {
setSyncState('local');
} else {
setSyncState('error');
@@ -168,7 +171,7 @@ export function SyncButton({ localPrefs, style, onSync }) {
: null,
}),
)}
- onClick={onSync}
+ onClick={sync}
>
{syncState === 'error' ? (
<AlertTriangle width={13} />
@@ -186,8 +189,12 @@ export function SyncButton({ localPrefs, style, onSync }) {
);
}
-function BudgetTitlebar({ globalPrefs, saveGlobalPrefs, localPrefs }) {
+function BudgetTitlebar() {
+ let maxMonths = useSelector(state => state.prefs.global.maxMonths);
+ let budgetType = useSelector(state => state.prefs.local.budgetType);
+ let { saveGlobalPrefs } = useActions();
let { sendEvent } = useContext(TitlebarContext);
+
let [loading, setLoading] = useState(false);
let [showTooltip, setShowTooltip] = useState(false);
@@ -202,14 +209,12 @@ function BudgetTitlebar({ globalPrefs, saveGlobalPrefs, localPrefs }) {
useEffect(() => {
setLoading(false);
- }, [localPrefs.budgetType]);
-
- let { budgetType } = localPrefs;
+ }, [budgetType]);
return (
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<MonthCountSelector
- maxMonths={globalPrefs.maxMonths || 1}
+ maxMonths={maxMonths || 1}
onChange={value => saveGlobalPrefs({ maxMonths: value })}
/>
{reportBudgetEnabled && (
@@ -273,26 +278,18 @@ function BudgetTitlebar({ globalPrefs, saveGlobalPrefs, localPrefs }) {
);
}
-function Titlebar({
- globalPrefs,
- saveGlobalPrefs,
- savePrefs,
- localPrefs,
- floatingSidebar,
- style,
- sync,
-}) {
+export default function Titlebar({ style }) {
let navigate = useNavigate();
let location = useLocation();
let sidebar = useSidebar();
let { isNarrowWidth } = useResponsive();
- const serverURL = useServerURL();
+ let serverURL = useServerURL();
+ let floatingSidebar = useSelector(
+ state => state.prefs.global.floatingSidebar,
+ );
let privacyModeFeatureFlag = useFeatureFlag('privacyMode');
let themesFlag = useFeatureFlag('themes');
- let onTogglePrivacy = enabled => {
- savePrefs({ isPrivacyEnabled: enabled });
- };
return isNarrowWidth ? null : (
<View
@@ -359,46 +356,16 @@ function Titlebar({
<Route path="/accounts/:id" element={<AccountSyncCheck />} />
- <Route
- path="/budget"
- element={
- <BudgetTitlebar
- globalPrefs={globalPrefs}
- saveGlobalPrefs={saveGlobalPrefs}
- localPrefs={localPrefs}
- />
- }
- />
+ <Route path="/budget" element={<BudgetTitlebar />} />
<Route path="*" element={null} />
</Routes>
<View style={{ flex: 1 }} />
<UncategorizedButton />
{themesFlag && <ThemeSelector />}
- {privacyModeFeatureFlag && (
- <PrivacyButton
- localPrefs={localPrefs}
- onTogglePrivacy={onTogglePrivacy}
- />
- )}
- {serverURL ? (
- <SyncButton
- style={{ marginLeft: 10 }}
- localPrefs={localPrefs}
- onSync={sync}
- />
- ) : null}
+ {privacyModeFeatureFlag && <PrivacyButton />}
+ {serverURL ? <SyncButton style={{ marginLeft: 10 }} /> : null}
<LoggedInUser style={{ marginLeft: 10 }} />
</View>
);
}
-
-export default connect(
- state => ({
- globalPrefs: state.prefs.global,
- localPrefs: state.prefs.local,
- userData: state.user.data,
- floatingSidebar: state.prefs.global.floatingSidebar,
- }),
- actions,
-)(Titlebar);
diff --git a/packages/desktop-client/src/components/UpdateNotification.js b/packages/desktop-client/src/components/UpdateNotification.js
index f7762bbad9..12e1a15933 100644
--- a/packages/desktop-client/src/components/UpdateNotification.js
+++ b/packages/desktop-client/src/components/UpdateNotification.js
@@ -1,10 +1,7 @@
import React from 'react';
-import { connect } from 'react-redux';
-
-import { bindActionCreators } from 'redux';
-
-import * as actions from 'loot-core/src/client/actions';
+import { useSelector } from 'react-redux';
+import { useActions } from '../hooks/useActions';
import Close from '../icons/v1/Close';
import { colors } from '../style';
@@ -18,12 +15,14 @@ function closeNotification(setAppState) {
});
}
-function UpdateNotification({
- updateInfo,
- showUpdateNotification,
- updateApp,
- setAppState,
-}) {
+export default function UpdateNotification() {
+ let updateInfo = useSelector(state => state.app.updateInfo);
+ let showUpdateNotification = useSelector(
+ state => state.app.showUpdateNotification,
+ );
+
+ let { updateApp, setAppState } = useActions();
+
if (updateInfo && showUpdateNotification) {
let notes = updateInfo.releaseNotes;
@@ -86,11 +85,3 @@ function UpdateNotification({
return null;
}
-
-export default connect(
- state => ({
- updateInfo: state.app.updateInfo,
- showUpdateNotification: state.app.showUpdateNotification,
- }),
- dispatch => bindActionCreators(actions, dispatch),
-)(UpdateNotification);
diff --git a/packages/desktop-client/src/components/accounts/AccountSyncCheck.js b/packages/desktop-client/src/components/accounts/AccountSyncCheck.js
index df6dcc7e0f..17bd824172 100644
--- a/packages/desktop-client/src/components/accounts/AccountSyncCheck.js
+++ b/packages/desktop-client/src/components/accounts/AccountSyncCheck.js
@@ -1,10 +1,9 @@
import React, { useState } from 'react';
-import { connect } from 'react-redux';
+import { useSelector } from 'react-redux';
import { useParams } from 'react-router-dom';
-import * as actions from 'loot-core/src/client/actions';
-
import { authorizeBank } from '../../gocardless';
+import { useActions } from '../../hooks/useActions';
import ExclamationOutline from '../../icons/v1/ExclamationOutline';
import { colors } from '../../style';
import { View, Button, Tooltip, ExternalLink } from '../common';
@@ -46,12 +45,11 @@ function getErrorMessage(type, code) {
);
}
-function AccountSyncCheck({
- accounts,
- failedAccounts,
- unlinkAccount,
- pushModal,
-}) {
+export default function AccountSyncCheck() {
+ let accounts = useSelector(state => state.queries.accounts);
+ let failedAccounts = useSelector(state => state.account.failedAccounts);
+ let { unlinkAccount, pushModal } = useActions();
+
let { id } = useParams();
let [open, setOpen] = useState(false);
if (!failedAccounts) {
@@ -133,11 +131,3 @@ function AccountSyncCheck({
</View>
);
}
-
-export default connect(
- state => ({
- accounts: state.queries.accounts,
- failedAccounts: state.account.failedAccounts,
- }),
- actions,
-)(AccountSyncCheck);
diff --git a/packages/desktop-client/src/components/accounts/MobileAccount.js b/packages/desktop-client/src/components/accounts/MobileAccount.js
index f647f93af9..b4ec654368 100644
--- a/packages/desktop-client/src/components/accounts/MobileAccount.js
+++ b/packages/desktop-client/src/components/accounts/MobileAccount.js
@@ -1,5 +1,5 @@
import React, { useEffect, useMemo, useState } from 'react';
-import { connect, useDispatch, useSelector } from 'react-redux';
+import { useDispatch, useSelector } from 'react-redux';
import { useParams, useNavigate } from 'react-router-dom';
import debounce from 'debounce';
@@ -20,8 +20,9 @@ import {
ungroupTransactions,
} from 'loot-core/src/shared/transactions';
+import { useActions } from '../../hooks/useActions';
+import { useSetThemeColor } from '../../hooks/useSetThemeColor';
import { colors } from '../../style';
-import { withThemeColor } from '../../util/withThemeColor';
import SyncRefresh from '../SyncRefresh';
import AccountDetails from './MobileAccountDetails';
@@ -68,7 +69,10 @@ function PreviewTransactions({ accountId, children }) {
let paged;
-function Account(props) {
+export default function Account(props) {
+ const accounts = useSelector(state => state.queries.accounts);
+ const { syncAndDownload } = useActions();
+
const navigate = useNavigate();
const [transactions, setTransactions] = useState([]);
const [searchText, setSearchText] = useState('');
@@ -133,7 +137,7 @@ function Account(props) {
if (state.categories.length === 0) {
await actionCreators.getCategories();
}
- if (props.accounts.length === 0) {
+ if (accounts.length === 0) {
await actionCreators.getAccounts();
}
@@ -164,11 +168,13 @@ function Account(props) {
useEffect(updateSearchQuery, [searchText, currentQuery, state.dateFormat]);
- if (!props.accounts || !props.accounts.length) {
+ useSetThemeColor(colors.n11);
+
+ if (!accounts || !accounts.length) {
return null;
}
- const account = props.accounts.find(acct => acct.id === accountId);
+ const account = accounts.find(acct => acct.id === accountId);
const isNewTransaction = id => {
return state.newTransactions.includes(id);
@@ -223,7 +229,7 @@ function Account(props) {
};
const onRefresh = async () => {
- await props.syncAndDownload();
+ await syncAndDownload();
};
let balance = queries.accountBalance(account);
@@ -246,7 +252,7 @@ function Account(props) {
{...actionCreators}
key={numberFormat + hideFraction}
account={account}
- accounts={props.accounts}
+ accounts={accounts}
categories={state.categories}
payees={state.payees}
transactions={transactions}
@@ -273,14 +279,3 @@ function Account(props) {
</SyncRefresh>
);
}
-
-export default connect(
- state => ({
- accounts: state.queries.accounts,
- newTransactions: state.queries.newTransactions,
- updatedAccounts: state.queries.updatedAccounts,
- categories: state.queries.categories.list,
- prefs: state.prefs.local,
- }),
- actions,
-)(withThemeColor(colors.n11)(Account));
diff --git a/packages/desktop-client/src/components/accounts/MobileAccounts.js b/packages/desktop-client/src/components/accounts/MobileAccounts.js
index cd03c6a137..7b2ed03e53 100644
--- a/packages/desktop-client/src/components/accounts/MobileAccounts.js
+++ b/packages/desktop-client/src/components/accounts/MobileAccounts.js
@@ -1,12 +1,12 @@
import React, { Component, useEffect, useState } from 'react';
-import { connect } from 'react-redux';
+import { useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
-import * as actions from 'loot-core/src/client/actions';
import * as queries from 'loot-core/src/client/queries';
+import { useActions } from '../../hooks/useActions';
+import { useSetThemeColor } from '../../hooks/useSetThemeColor';
import { colors, styles } from '../../style';
-import { withThemeColor } from '../../util/withThemeColor';
import { Button, Text, TextOneLine, View } from '../common';
import { Page } from '../Page';
import CellValue from '../spreadsheet/CellValue';
@@ -226,20 +226,31 @@ class AccountList extends Component {
}
}
-function Accounts(props) {
+export default function Accounts() {
+ let accounts = useSelector(state => state.queries.accounts);
+ let newTransactions = useSelector(state => state.queries.newTransactions);
+ let updatedAccounts = useSelector(state => state.queries.updatedAccounts);
+ let categories = useSelector(state => state.queries.categories.list);
+ let numberFormat = useSelector(
+ state => state.prefs.local.numberFormat || 'comma-dot',
+ );
+ let hideFraction = useSelector(
+ state => state.prefs.local.hideFraction || false,
+ );
+
+ let { getCategories, getAccounts } = useActions();
+
const transactions = useState({});
const navigate = useNavigate();
useEffect(() => {
- const getAccounts = async () => {
- if (props.categories.length === 0) {
- await props.getCategories();
+ (async () => {
+ if (categories.length === 0) {
+ await getCategories();
}
- props.getAccounts();
- };
-
- getAccounts();
+ getAccounts();
+ })();
}, []);
// const sync = async () => {
@@ -254,9 +265,7 @@ function Accounts(props) {
navigate(`/transaction/${transaction}`);
};
- let { accounts, categories, newTransactions, updatedAccounts, prefs } = props;
- let numberFormat = prefs.numberFormat || 'comma-dot';
- let hideFraction = prefs.hideFraction || false;
+ useSetThemeColor(colors.b2);
return (
<View style={{ flex: 1 }}>
@@ -282,14 +291,3 @@ function Accounts(props) {
</View>
);
}
-
-export default connect(
- state => ({
- accounts: state.queries.accounts,
- newTransactions: state.queries.newTransactions,
- updatedAccounts: state.queries.updatedAccounts,
- categories: state.queries.categories.list,
- prefs: state.prefs.local,
- }),
- actions,
-)(withThemeColor(colors.b2)(Accounts));
diff --git a/packages/desktop-client/src/components/budget/DynamicBudgetTable.js b/packages/desktop-client/src/components/budget/DynamicBudgetTable.js
index 5acac8e161..3388ead1cf 100644
--- a/packages/desktop-client/src/components/budget/DynamicBudgetTable.js
+++ b/packages/desktop-client/src/components/budget/DynamicBudgetTable.js
@@ -1,6 +1,8 @@
import React, { forwardRef, useEffect } from 'react';
+import { useSelector } from 'react-redux';
import AutoSizer from 'react-virtualized-auto-sizer';
+import { useActions } from '../../hooks/useActions';
import { View } from '../common';
import { useBudgetMonthCount } from './BudgetMonthCountContext';
@@ -41,7 +43,9 @@ const DynamicBudgetTableInner = forwardRef(
},
ref,
) => {
+ let prefs = useSelector(state => state.prefs.local);
let { setDisplayMax } = useBudgetMonthCount();
+ let actions = useActions();
let numPossible = getNumPossibleMonths(width);
let numMonths = Math.min(numPossible, maxMonths);
@@ -79,6 +83,8 @@ const DynamicBudgetTableInner = forwardRef(
startMonth={startMonth}
numMonths={numMonths}
monthBounds={monthBounds}
+ prefs={prefs}
+ {...actions}
{...props}
/>
</View>
diff --git a/packages/desktop-client/src/components/budget/MobileBudget.js b/packages/desktop-client/src/components/budget/MobileBudget.js
index e2f2bc9830..0591308f46 100644
--- a/packages/desktop-client/src/components/budget/MobileBudget.js
+++ b/packages/desktop-client/src/components/budget/MobileBudget.js
@@ -1,7 +1,6 @@
import React, { Component } from 'react';
-import { connect } from 'react-redux';
+import { useSelector } from 'react-redux';
-import * as actions from 'loot-core/src/client/actions';
import { useSpreadsheet } from 'loot-core/src/client/SpreadsheetProvider';
import { send, listen } from 'loot-core/src/platform/client/fetch';
import {
@@ -11,9 +10,10 @@ import {
} from 'loot-core/src/shared/categories';
import * as monthUtils from 'loot-core/src/shared/months';
+import { useActions } from '../../hooks/useActions';
+import { useSetThemeColor } from '../../hooks/useSetThemeColor';
import AnimatedLoading from '../../icons/AnimatedLoading';
import { colors } from '../../style';
-import { withThemeColor } from '../../util/withThemeColor';
import { View } from '../common';
import SyncRefresh from '../SyncRefresh';
@@ -292,18 +292,28 @@ class Budget extends Component {
}
}
-function BudgetWrapper(props) {
+export default function BudgetWrapper() {
+ let categoryGroups = useSelector(state => state.queries.categories.grouped);
+ let categories = useSelector(state => state.queries.categories.list);
+ let budgetType = useSelector(
+ state => state.prefs.local.budgetType || 'rollover',
+ );
+ let prefs = useSelector(state => state.prefs.local);
+ let initialBudgetMonth = useSelector(state => state.app.budgetMonth);
+
+ let actions = useActions();
let spreadsheet = useSpreadsheet();
- return <Budget {...props} spreadsheet={spreadsheet} />;
-}
-export default connect(
- state => ({
- categoryGroups: state.queries.categories.grouped,
- categories: state.queries.categories.list,
- budgetType: state.prefs.local.budgetType || 'rollover',
- prefs: state.prefs.local,
- initialBudgetMonth: state.app.budgetMonth,
- }),
- actions,
-)(withThemeColor(colors.p5)(BudgetWrapper));
+ useSetThemeColor(colors.p5);
+ return (
+ <Budget
+ categoryGroups={categoryGroups}
+ categories={categories}
+ budgetType={budgetType}
+ prefs={prefs}
+ initialBudgetMonth={initialBudgetMonth}
+ {...actions}
+ spreadsheet={spreadsheet}
+ />
+ );
+}
diff --git a/packages/desktop-client/src/components/budget/MobileBudgetTable.js b/packages/desktop-client/src/components/budget/MobileBudgetTable.js
index acc5c077d2..525063953c 100644
--- a/packages/desktop-client/src/components/budget/MobileBudgetTable.js
+++ b/packages/desktop-client/src/components/budget/MobileBudgetTable.js
@@ -6,11 +6,9 @@ import React, { Component, memo, PureComponent } from 'react';
// } from 'react-native-gesture-handler';
// import Animated, { Easing } from 'react-native-reanimated';
// import AndroidKeyboardAvoidingView from './AndroidKeyboardAvoidingView';
-import { connect } from 'react-redux';
import memoizeOne from 'memoize-one';
-import * as actions from 'loot-core/src/client/actions';
import { rolloverBudget, reportBudget } from 'loot-core/src/client/queries';
import * as monthUtils from 'loot-core/src/shared/months';
import { amountToInteger, integerToAmount } from 'loot-core/src/shared/util';
@@ -994,15 +992,13 @@ export class BudgetTable extends Component {
}
}
-function UnconnectedBudgetHeader({
+function BudgetHeader({
currentMonth,
monthBounds,
editMode,
onDone,
onPrevMonth,
onNextMonth,
- sync,
- localPrefs,
}) {
// let [menuOpen, setMenuOpen] = useState(false);
@@ -1112,8 +1108,6 @@ function UnconnectedBudgetHeader({
paddingLeft: 12,
paddingRight: 12,
}}
- localPrefs={localPrefs}
- onSync={sync}
/>
{/* <Button
type="bare"
@@ -1155,10 +1149,3 @@ function UnconnectedBudgetHeader({
</View>
);
}
-
-const BudgetHeader = connect(
- state => ({
- localPrefs: state.prefs.local,
- }),
- actions,
-)(UnconnectedBudgetHeader);
diff --git a/packages/desktop-client/src/components/budget/index.js b/packages/desktop-client/src/components/budget/index.js
index 6ca1753094..f41948e24c 100644
--- a/packages/desktop-client/src/components/budget/index.js
+++ b/packages/desktop-client/src/components/budget/index.js
@@ -1,8 +1,7 @@
import React, { memo, PureComponent, useContext, useMemo } from 'react';
-import { connect } from 'react-redux';
+import { useSelector } from 'react-redux';
import { useLocation, useMatch, useNavigate } from 'react-router-dom';
-import * as actions from 'loot-core/src/client/actions';
import { useSpreadsheet } from 'loot-core/src/client/SpreadsheetProvider';
import { send, listen } from 'loot-core/src/platform/client/fetch';
import {
@@ -17,6 +16,7 @@ import {
} from 'loot-core/src/shared/categories';
import * as monthUtils from 'loot-core/src/shared/months';
+import { useActions } from '../../hooks/useActions';
import useFeatureFlag from '../../hooks/useFeatureFlag';
import { styles } from '../../style';
import { View } from '../common';
@@ -523,7 +523,21 @@ const RolloverBudgetSummary = memo(props => {
);
});
-function BudgetWrapper(props) {
+export default function BudgetWrapper(props) {
+ let startMonth = useSelector(state => state.prefs.local['budget.startMonth']);
+ let collapsedPrefs = useSelector(
+ state => state.prefs.local['budget.collapsed'],
+ );
+ let summaryCollapsed = useSelector(
+ state => state.prefs.local['budget.summaryCollapsed'],
+ );
+ let budgetType = useSelector(
+ state => state.prefs.local.budgetType || 'rollover',
+ );
+ let maxMonths = useSelector(state => state.prefs.global.maxMonths);
+ let categoryGroups = useSelector(state => state.queries.categories.grouped);
+
+ let actions = useActions();
let spreadsheet = useSpreadsheet();
let titlebar = useContext(TitlebarContext);
let location = useLocation();
@@ -568,7 +582,13 @@ function BudgetWrapper(props) {
]}
>
<Budget
- {...props}
+ startMonth={startMonth}
+ collapsedPrefs={collapsedPrefs}
+ summaryCollapsed={summaryCollapsed}
+ budgetType={budgetType}
+ maxMonths={maxMonths}
+ categoryGroups={categoryGroups}
+ {...actions}
reportComponents={reportComponents}
rolloverComponents={rolloverComponents}
spreadsheet={spreadsheet}
@@ -579,15 +599,3 @@ function BudgetWrapper(props) {
</View>
);
}
-
-export default connect(
- state => ({
- startMonth: state.prefs.local['budget.startMonth'],
- collapsedPrefs: state.prefs.local['budget.collapsed'],
- summaryCollapsed: state.prefs.local['budget.summaryCollapsed'],
- budgetType: state.prefs.local.budgetType || 'rollover',
- maxMonths: state.prefs.global.maxMonths,
- categoryGroups: state.queries.categories.grouped,
- }),
- actions,
-)(BudgetWrapper);
diff --git a/packages/desktop-client/src/components/budget/misc.js b/packages/desktop-client/src/components/budget/misc.js
index d38c44f18d..4c1dacdda2 100644
--- a/packages/desktop-client/src/components/budget/misc.js
+++ b/packages/desktop-client/src/components/budget/misc.js
@@ -6,11 +6,7 @@ import React, {
useState,
useMemo,
} from 'react';
-import { connect } from 'react-redux';
-import { bindActionCreators } from 'redux';
-
-import * as actions from 'loot-core/src/client/actions';
import * as monthUtils from 'loot-core/src/shared/months';
import ExpandArrow from '../../icons/v0/ExpandArrow';
@@ -45,7 +41,7 @@ function getScrollbarWidth() {
return Math.max(styles.scrollbarWidth - 2, 0);
}
-class BudgetTable extends Component {
+export class BudgetTable extends Component {
constructor(props) {
super(props);
this.budgetCategoriesRef = createRef();
@@ -315,17 +311,6 @@ class BudgetTable extends Component {
}
}
-const connected = connect(
- state => ({
- prefs: state.prefs.local,
- }),
- dispatch => bindActionCreators(actions, dispatch),
- null,
- { forwardRef: true },
-)(BudgetTable);
-
-export { connected as BudgetTable };
-
function SidebarCategory({
innerRef,
category,
diff --git a/packages/desktop-client/src/components/manager/BudgetList.js b/packages/desktop-client/src/components/manager/BudgetList.js
index b5300577a4..6b82f0ae0f 100644
--- a/packages/desktop-client/src/components/manager/BudgetList.js
+++ b/packages/desktop-client/src/components/manager/BudgetList.js
@@ -1,9 +1,10 @@
import React, { useState, useRef } from 'react';
-import { connect } from 'react-redux';
+import { useSelector } from 'react-redux';
import * as actions from 'loot-core/src/client/actions';
import { isNonProductionEnvironment } from 'loot-core/src/shared/environment';
+import { useActions } from '../../hooks/useActions';
import Loading from '../../icons/AnimatedLoading';
import CloudCheck from '../../icons/v1/CloudCheck';
import CloudDownload from '../../icons/v1/CloudDownload';
@@ -238,15 +239,18 @@ function RefreshButton({ onRefresh }) {
);
}
-function BudgetList({
- files = [],
- getUserData,
- loadAllFiles,
- pushModal,
- loadBudget,
- createBudget,
- downloadBudget,
-}) {
+export default function BudgetList() {
+ let files = useSelector(state => state.budgets.allFiles || []);
+
+ let {
+ getUserData,
+ loadAllFiles,
+ pushModal,
+ loadBudget,
+ createBudget,
+ downloadBudget,
+ } = useActions();
+
const [creating, setCreating] = useState(false);
const onCreate = ({ testMode } = {}) => {
@@ -342,11 +346,3 @@ function BudgetList({
</View>
);
}
-
-export default connect(
- state => ({
- files: state.budgets.allFiles,
- isLoggedIn: !!state.user.data,
- }),
- actions,
-)(BudgetList);
diff --git a/packages/desktop-client/src/components/manager/ConfigServer.js b/packages/desktop-client/src/components/manager/ConfigServer.js
index b2dd63b68e..9e83ebb2f9 100644
--- a/packages/desktop-client/src/components/manager/ConfigServer.js
+++ b/packages/desktop-client/src/components/manager/ConfigServer.js
@@ -9,7 +9,7 @@ import {
isElectron,
} from 'loot-core/src/shared/environment';
-import { useSetThemeColor } from '../../hooks';
+import { useSetThemeColor } from '../../hooks/useSetThemeColor';
import { colors } from '../../style';
import { View, Text, Button, ButtonWithLoading } from '../common';
import { useServerURL, useSetServerURL } from '../ServerContext';
diff --git a/packages/desktop-client/src/components/manager/ManagementApp.js b/packages/desktop-client/src/components/manager/ManagementApp.js
index 7a36f03299..b80ca31e57 100644
--- a/packages/desktop-client/src/components/manager/ManagementApp.js
+++ b/packages/desktop-client/src/components/manager/ManagementApp.js
@@ -1,9 +1,8 @@
import React, { useEffect } from 'react';
-import { connect } from 'react-redux';
+import { useSelector } from 'react-redux';
import { Navigate, BrowserRouter, Route, Routes } from 'react-router-dom';
-import * as actions from 'loot-core/src/client/actions';
-
+import { useActions } from '../../hooks/useActions';
import { theme } from '../../style';
import tokens from '../../tokens';
import { ExposeNavigate } from '../../util/router-tools';
@@ -47,15 +46,15 @@ function Version() {
);
}
-function ManagementApp({
- isLoading,
- files,
- userData,
- managerHasInitialized,
- setAppState,
- getUserData,
- loadAllFiles,
-}) {
+export default function ManagementApp({ isLoading }) {
+ let files = useSelector(state => state.budgets.allFiles);
+ let userData = useSelector(state => state.user.data);
+ let managerHasInitialized = useSelector(
+ state => state.app.managerHasInitialized,
+ );
+
+ let { setAppState, getUserData, loadAllFiles } = useActions();
+
// runs on mount only
useEffect(() => {
// An action may have been triggered from outside, and we don't
@@ -208,14 +207,3 @@ function ManagementApp({
</BrowserRouter>
);
}
-
-export default connect(state => {
- let { modalStack } = state.modals;
-
- return {
- files: state.budgets.allFiles,
- userData: state.user.data,
- managerHasInitialized: state.app.managerHasInitialized,
- currentModals: modalStack.map(modal => modal.name),
- };
-}, actions)(ManagementApp);
diff --git a/packages/desktop-client/src/components/manager/Modals.js b/packages/desktop-client/src/components/manager/Modals.js
index a77e6356d8..f090c0b6d4 100644
--- a/packages/desktop-client/src/components/manager/Modals.js
+++ b/packages/desktop-client/src/components/manager/Modals.js
@@ -1,10 +1,7 @@
import React from 'react';
-import { connect } from 'react-redux';
-
-import { bindActionCreators } from 'redux';
-
-import * as actions from 'loot-core/src/client/actions';
+import { useSelector } from 'react-redux';
+import { useActions } from '../../hooks/useActions';
import { View } from '../common';
import CreateEncryptionKey from '../modals/CreateEncryptionKey';
import FixEncryptionKey from '../modals/FixEncryptionKey';
@@ -16,7 +13,11 @@ import ImportActual from './ImportActual';
import ImportYNAB4 from './ImportYNAB4';
import ImportYNAB5 from './ImportYNAB5';
-function Modals({ modalStack, isHidden, actions }) {
+export default function Modals() {
+ let modalStack = useSelector(state => state.modals.modalStack);
+ let isHidden = useSelector(state => state.modals.isHidden);
+ let actions = useActions();
+
let stack = modalStack.map(({ name, options }, idx) => {
const modalProps = {
onClose: actions.popModal,
@@ -89,12 +90,3 @@ function Modals({ modalStack, isHidden, actions }) {
return <View style={{ flex: 1, padding: 50 }}>{stack}</View>;
}
-
-export default connect(
- state => ({
- modalStack: state.modals.modalStack,
- isHidden: state.modals.isHidden,
- budgets: state.budgets.budgets,
- }),
- dispatch => ({ actions: bindActionCreators(actions, dispatch) }),
-)(Modals);
diff --git a/packages/desktop-client/src/components/manager/WelcomeScreen.js b/packages/desktop-client/src/components/manager/WelcomeScreen.js
index 18e1b1bc40..f0765c4063 100644
--- a/packages/desktop-client/src/components/manager/WelcomeScreen.js
+++ b/packages/desktop-client/src/components/manager/WelcomeScreen.js
@@ -1,12 +1,12 @@
import React from 'react';
-import { connect } from 'react-redux';
-
-import * as actions from 'loot-core/src/client/actions';
+import { useActions } from '../../hooks/useActions';
import { colors, styles } from '../../style';
import { View, Button, Text, P, ExternalLink } from '../common';
-function WelcomeScreen({ createBudget, pushModal }) {
+export default function WelcomeScreen() {
+ let { createBudget, pushModal } = useActions();
+
return (
<View
style={{
@@ -66,5 +66,3 @@ function WelcomeScreen({ createBudget, pushModal }) {
</View>
);
}
-
-export default connect(null, actions)(WelcomeScreen);
diff --git a/packages/desktop-client/src/components/modals/EditField.js b/packages/desktop-client/src/components/modals/EditField.js
index 5dcf73bf39..4d5f7ea1fe 100644
--- a/packages/desktop-client/src/components/modals/EditField.js
+++ b/packages/desktop-client/src/components/modals/EditField.js
@@ -1,12 +1,12 @@
import React from 'react';
-import { connect } from 'react-redux';
+import { useSelector } from 'react-redux';
import { parseISO, format as formatDate, parse as parseDate } from 'date-fns';
-import * as actions from 'loot-core/src/client/actions';
import { currentDay, dayFromDate } from 'loot-core/src/shared/months';
import { amountToInteger } from 'loot-core/src/shared/util';
+import { useActions } from '../../hooks/useActions';
import { colors } from '../../style';
import AccountAutocomplete from '../autocomplete/AccountAutocomplete';
import CategoryAutocomplete from '../autocomplete/CategorySelect';
@@ -15,17 +15,16 @@ import { View, Modal, Input } from '../common';
import { SectionLabel } from '../forms';
import DateSelect from '../select/DateSelect';
-function EditField({
- actions,
- modalProps,
- name,
- accounts,
- categoryGroups,
- payees,
- onSubmit,
- dateFormat,
- createPayee,
-}) {
+export default function EditField({ modalProps, name, onSubmit }) {
+ let dateFormat = useSelector(
+ state => state.prefs.local.dateFormat || 'MM/dd/yyyy',
+ );
+ let categoryGroups = useSelector(state => state.queries.categories.grouped);
+ let accounts = useSelector(state => state.queries.accounts);
+ let payees = useSelector(state => state.queries.payees);
+
+ let { createPayee } = useActions();
+
function onSelect(value) {
if (value != null) {
// Process the value if needed
@@ -182,13 +181,3 @@ function EditField({
</Modal>
);
}
-
-export default connect(
- state => ({
- dateFormat: state.prefs.local.dateFormat || 'MM/dd/yyyy',
- categoryGroups: state.queries.categories.grouped,
- accounts: state.queries.accounts,
- payees: state.queries.payees,
- }),
- actions,
-)(EditField);
diff --git a/packages/desktop-client/src/components/payees/ManagePayeesWithData.js b/packages/desktop-client/src/components/payees/ManagePayeesWithData.js
index a83b521abc..01cced13d5 100644
--- a/packages/desktop-client/src/components/payees/ManagePayeesWithData.js
+++ b/packages/desktop-client/src/components/payees/ManagePayeesWithData.js
@@ -1,23 +1,21 @@
import React, { useState, useEffect, useRef } from 'react';
-import { connect } from 'react-redux';
+import { useSelector } from 'react-redux';
-import * as actions from 'loot-core/src/client/actions';
import { send, listen } from 'loot-core/src/platform/client/fetch';
import { applyChanges } from 'loot-core/src/shared/util';
+import { useActions } from '../../hooks/useActions';
+
import { ManagePayees } from '.';
-function ManagePayeesWithData({
- modalProps,
- initialSelectedIds,
- lastUndoState,
- initialPayees,
- categoryGroups,
- initiallyLoadPayees,
- getPayees,
- setLastUndoState,
- pushModal,
-}) {
+export default function ManagePayeesWithData({ initialSelectedIds }) {
+ let initialPayees = useSelector(state => state.queries.payees);
+ let lastUndoState = useSelector(state => state.app.lastUndoState);
+ let categoryGroups = useSelector(state => state.queries.categories.grouped);
+
+ let { initiallyLoadPayees, getPayees, setLastUndoState, pushModal } =
+ useActions();
+
let [payees, setPayees] = useState(initialPayees);
let [ruleCounts, setRuleCounts] = useState({ value: new Map() });
let [orphans, setOrphans] = useState({ value: new Map() });
@@ -121,7 +119,6 @@ function ManagePayeesWithData({
return (
<ManagePayees
ref={payeesRef}
- modalProps={modalProps}
payees={payees}
ruleCounts={ruleCounts.value}
orphanedPayees={orphans}
@@ -165,12 +162,3 @@ function ManagePayeesWithData({
/>
);
}
-
-export default connect(
- state => ({
- initialPayees: state.queries.payees,
- lastUndoState: state.app.lastUndoState,
- categoryGroups: state.queries.categories.grouped,
- }),
- actions,
-)(ManagePayeesWithData);
diff --git a/packages/desktop-client/src/components/payees/index.js b/packages/desktop-client/src/components/payees/index.js
index 6b763a4c0a..dd6ea78441 100644
--- a/packages/desktop-client/src/components/payees/index.js
+++ b/packages/desktop-client/src/components/payees/index.js
@@ -338,7 +338,6 @@ function PayeeMenu({ payeesById, selectedPayees, onDelete, onMerge, onClose }) {
export const ManagePayees = forwardRef(
(
{
- modalProps,
payees,
ruleCounts,
orphanedPayees,
diff --git a/packages/desktop-client/src/components/reports/NetWorth.js b/packages/desktop-client/src/components/reports/NetWorth.js
index c6a7507b05..343568eeba 100644
--- a/packages/desktop-client/src/components/reports/NetWorth.js
+++ b/packages/desktop-client/src/components/reports/NetWorth.js
@@ -1,10 +1,8 @@
import React, { useState, useEffect, useMemo } from 'react';
-import { connect } from 'react-redux';
+import { useSelector } from 'react-redux';
import * as d from 'date-fns';
-import { bindActionCreators } from 'redux';
-import * as actions from 'loot-core/src/client/actions';
import { send } from 'loot-core/src/platform/client/fetch';
import * as monthUtils from 'loot-core/src/shared/months';
import { integerToCurrency } from 'loot-core/src/shared/util';
@@ -20,7 +18,8 @@ import Header from './Header';
import useReport from './useReport';
import { fromDateRepr } from './util';
-function NetWorth({ accounts }) {
+export default function NetWorth() {
+ let accounts = useSelector(state => state.queries.accounts);
const {
filters,
saved,
@@ -140,8 +139,3 @@ function NetWorth({ accounts }) {
</View>
);
}
-
-export default connect(
- state => ({ accounts: state.queries.accounts }),
- dispatch => bindActionCreators(actions, dispatch),
-)(NetWorth);
diff --git a/packages/desktop-client/src/components/reports/Overview.js b/packages/desktop-client/src/components/reports/Overview.js
index 31a5f14bd9..0ea17ef09c 100644
--- a/packages/desktop-client/src/components/reports/Overview.js
+++ b/packages/desktop-client/src/components/reports/Overview.js
@@ -1,10 +1,8 @@
import React, { useMemo } from 'react';
-import { connect } from 'react-redux';
+import { useSelector } from 'react-redux';
-import { bindActionCreators } from 'redux';
import { VictoryBar, VictoryGroup, VictoryVoronoiContainer } from 'victory';
-import * as actions from 'loot-core/src/client/actions';
import * as monthUtils from 'loot-core/src/shared/months';
import { integerToCurrency } from 'loot-core/src/shared/util';
@@ -221,7 +219,8 @@ function CashFlowCard() {
);
}
-function Overview({ accounts }) {
+export default function Overview() {
+ let accounts = useSelector(state => state.queries.accounts);
return (
<View
style={[
@@ -263,8 +262,3 @@ function Overview({ accounts }) {
</View>
);
}
-
-export default connect(
- state => ({ accounts: state.queries.accounts }),
- dispatch => bindActionCreators(actions, dispatch),
-)(Overview);
diff --git a/packages/desktop-client/src/components/settings/Encryption.js b/packages/desktop-client/src/components/settings/Encryption.js
index e381ad66aa..bbedaa0529 100644
--- a/packages/desktop-client/src/components/settings/Encryption.js
+++ b/packages/desktop-client/src/components/settings/Encryption.js
@@ -1,20 +1,25 @@
import React from 'react';
+import { useSelector } from 'react-redux';
+import { useActions } from '../../hooks/useActions';
import { colors } from '../../style';
import { Text, Button, ExternalLink } from '../common';
import { useServerURL } from '../ServerContext';
import { Setting } from './UI';
-export default function EncryptionSettings({ prefs, pushModal }) {
+export default function EncryptionSettings() {
+ const { pushModal } = useActions();
const serverURL = useServerURL();
+ const encryptKeyId = useSelector(state => state.prefs.local.encryptKeyId);
+
const missingCryptoAPI = !(window.crypto && crypto.subtle);
function onChangeKey() {
pushModal('create-encryption-key', { recreate: true });
}
- return prefs.encryptKeyId ? (
+ return encryptKeyId ? (
<Setting
primaryAction={<Button onClick={onChangeKey}>Generate new key</Button>}
>
diff --git a/packages/desktop-client/src/components/settings/Export.js b/packages/desktop-client/src/components/settings/Export.js
index 6f2bc9aa72..1417b5ff37 100644
--- a/packages/desktop-client/src/components/settings/Export.js
+++ b/packages/desktop-client/src/components/settings/Export.js
@@ -1,4 +1,5 @@
import React from 'react';
+import { useSelector } from 'react-redux';
import { format } from 'date-fns';
@@ -8,12 +9,15 @@ import { Text, Button } from '../common';
import { Setting } from './UI';
-export default function ExportBudget({ prefs }) {
+export default function ExportBudget() {
+ let budgetId = useSelector(state => state.prefs.local.budgetId);
+ let encryptKeyId = useSelector(state => state.prefs.local.encryptKeyId);
+
async function onExport() {
let data = await send('export-budget');
window.Actual.saveFile(
data,
- `${format(new Date(), 'yyyy-MM-dd')}-${prefs.id}.zip`,
+ `${format(new Date(), 'yyyy-MM-dd')}-${budgetId}.zip`,
'Export budget',
);
}
@@ -26,7 +30,7 @@ export default function ExportBudget({ prefs }) {
imported into another Actual instance by closing an open file (if any),
then clicking the “Import file” button, then choosing “Actual.”
</Text>
- {prefs.encryptKeyId ? (
+ {encryptKeyId ? (
<Text>
Even though encryption is enabled, the exported zip file will not have
any encryption.
diff --git a/packages/desktop-client/src/components/settings/Format.js b/packages/desktop-client/src/components/settings/Format.js
index 009cc0930d..c92034ed75 100644
--- a/packages/desktop-client/src/components/settings/Format.js
+++ b/packages/desktop-client/src/components/settings/Format.js
@@ -1,7 +1,9 @@
import React from 'react';
+import { useSelector } from 'react-redux';
import { numberFormats } from 'loot-core/src/shared/util';
+import { useActions } from '../../hooks/useActions';
import tokens from '../../tokens';
import { Button, Select, Text, View } from '../common';
import { useSidebar } from '../FloatableSidebar';
@@ -45,7 +47,9 @@ function Column({ title, children }) {
);
}
-export default function FormatSettings({ prefs, savePrefs }) {
+export default function FormatSettings() {
+ let { savePrefs } = useActions();
+
function onFirstDayOfWeek(idx) {
savePrefs({ firstDayOfWeekIdx: idx });
}
@@ -64,9 +68,16 @@ export default function FormatSettings({ prefs, savePrefs }) {
}
let sidebar = useSidebar();
- let firstDayOfWeekIdx = prefs.firstDayOfWeekIdx || '0'; // Sunday
- let dateFormat = prefs.dateFormat || 'MM/dd/yyyy';
- let numberFormat = prefs.numberFormat || 'comma-dot';
+ let firstDayOfWeekIdx = useSelector(
+ state => state.prefs.local.firstDayOfWeekIdx || '0', // Sunday
+ );
+ let dateFormat = useSelector(
+ state => state.prefs.local.dateFormat || 'MM/dd/yyyy',
+ );
+ let numberFormat = useSelector(
+ state => state.prefs.local.numberFormat || 'comma-dot',
+ );
+ let hideFraction = useSelector(state => state.prefs.local.hideFraction);
return (
<Setting
@@ -88,12 +99,12 @@ export default function FormatSettings({ prefs, savePrefs }) {
<Column title="Numbers">
<Button bounce={false} style={{ padding: 0 }}>
<Select
- key={prefs.hideFraction} // needed because label does not update
+ key={hideFraction} // needed because label does not update
value={numberFormat}
onChange={onNumberFormat}
options={numberFormats.map(f => [
f.value,
- prefs.hideFraction ? f.labelNoFraction : f.label,
+ hideFraction ? f.labelNoFraction : f.label,
])}
style={{ padding: '2px 10px', fontSize: 15 }}
/>
@@ -102,7 +113,7 @@ export default function FormatSettings({ prefs, savePrefs }) {
<Text style={{ display: 'flex' }}>
<Checkbox
id="settings-textDecimal"
- checked={!!prefs.hideFraction}
+ checked={!!hideFraction}
onChange={onHideFraction}
/>
<label htmlFor="settings-textDecimal">Hide decimal places</label>
diff --git a/packages/desktop-client/src/components/settings/Global.js b/packages/desktop-client/src/components/settings/Global.js
index 65f516a332..318332e8c8 100644
--- a/packages/desktop-client/src/components/settings/Global.js
+++ b/packages/desktop-client/src/components/settings/Global.js
@@ -1,12 +1,17 @@
import React, { useState, useEffect, useRef } from 'react';
+import { useSelector } from 'react-redux';
+import { useActions } from '../../hooks/useActions';
import { colors } from '../../style';
import { Information } from '../alerts';
import { View, Text, Button } from '../common';
import { Setting } from './UI';
-export default function GlobalSettings({ globalPrefs, saveGlobalPrefs }) {
+export default function GlobalSettings() {
+ let documentDir = useSelector(state => state.prefs.global.documentDir);
+ let { saveGlobalPrefs } = useActions();
+
let [documentDirChanged, setDirChanged] = useState(false);
let dirScrolled = useRef(null);
@@ -57,7 +62,7 @@ export default function GlobalSettings({ globalPrefs, saveGlobalPrefs }) {
'::-webkit-scrollbar': { display: 'none' },
}}
>
- {globalPrefs.documentDir}
+ {documentDir}
</Text>
</Setting>
);
diff --git a/packages/desktop-client/src/components/settings/Reset.js b/packages/desktop-client/src/components/settings/Reset.js
index 16307b4160..d7afc7f86e 100644
--- a/packages/desktop-client/src/components/settings/Reset.js
+++ b/packages/desktop-client/src/components/settings/Reset.js
@@ -1,7 +1,9 @@
import React, { useState } from 'react';
+import { useSelector } from 'react-redux';
import { send } from 'loot-core/src/platform/client/fetch';
+import { useActions } from '../../hooks/useActions';
import { Text, ButtonWithLoading } from '../common';
import { Setting } from './UI';
@@ -34,7 +36,10 @@ export function ResetCache() {
);
}
-export function ResetSync({ isEnabled, resetSync }) {
+export function ResetSync() {
+ let isEnabled = useSelector(state => !!state.prefs.local.groupId);
+ let { resetSync } = useActions();
+
let [resetting, setResetting] = useState(false);
async function onResetSync() {
diff --git a/packages/desktop-client/src/components/settings/Themes.js b/packages/desktop-client/src/components/settings/Themes.js
index b48f756b0b..1322776b99 100644
--- a/packages/desktop-client/src/components/settings/Themes.js
+++ b/packages/desktop-client/src/components/settings/Themes.js
@@ -1,12 +1,15 @@
import React from 'react';
+import { useActions } from '../../hooks/useActions';
import { themeNames, useTheme } from '../../style';
import { Button, Select, Text } from '../common';
import { Setting } from './UI';
-export default function ThemeSettings({ saveGlobalPrefs }) {
+export default function ThemeSettings() {
let theme = useTheme();
+ let { saveGlobalPrefs } = useActions();
+
return (
<Setting
primaryAction={
diff --git a/packages/desktop-client/src/components/settings/index.js b/packages/desktop-client/src/components/settings/index.js
index d72b20d5a1..e0571dd2d1 100644
--- a/packages/desktop-client/src/components/settings/index.js
+++ b/packages/desktop-client/src/components/settings/index.js
@@ -1,18 +1,18 @@
import React, { useEffect } from 'react';
-import { connect } from 'react-redux';
+import { useSelector } from 'react-redux';
import { media } from 'glamor';
-import * as actions from 'loot-core/src/client/actions';
import * as Platform from 'loot-core/src/client/platform';
import { listen } from 'loot-core/src/platform/client/fetch';
+import { useActions } from '../../hooks/useActions';
import useFeatureFlag from '../../hooks/useFeatureFlag';
import useLatestVersion, { useIsOutdated } from '../../hooks/useLatestVersion';
+import { useSetThemeColor } from '../../hooks/useSetThemeColor';
import { useResponsive } from '../../ResponsiveProvider';
import { colors } from '../../style';
import tokens from '../../tokens';
-import { withThemeColor } from '../../util/withThemeColor';
import { View, Text, Button, Input, ExternalLink } from '../common';
import { FormField, FormLabel } from '../forms';
import { Page } from '../Page';
@@ -79,7 +79,10 @@ function IDName({ children }) {
return <Text style={{ fontWeight: 500 }}>{children}</Text>;
}
-function AdvancedAbout({ prefs }) {
+function AdvancedAbout() {
+ let budgetId = useSelector(state => state.prefs.local.id);
+ let groupId = useSelector(state => state.prefs.local.groupId);
+
return (
<Setting>
<Text>
@@ -89,10 +92,10 @@ function AdvancedAbout({ prefs }) {
to access the budget on the server.
</Text>
<Text>
- <IDName>Budget ID:</IDName> {prefs.id}
+ <IDName>Budget ID:</IDName> {budgetId}
</Text>
<Text style={{ color: colors.n5 }}>
- <IDName>Sync ID:</IDName> {prefs.groupId || '(none)'}
+ <IDName>Sync ID:</IDName> {groupId || '(none)'}
</Text>
{/* low priority todo: eliminate some or all of these, or decide when/if to show them */}
{/* <Text>
@@ -105,16 +108,14 @@ function AdvancedAbout({ prefs }) {
);
}
-function Settings({
- loadPrefs,
- savePrefs,
- saveGlobalPrefs,
- prefs,
- globalPrefs,
- pushModal,
- resetSync,
- closeBudget,
-}) {
+export default function Settings() {
+ let floatingSidebar = useSelector(
+ state => state.prefs.global.floatingSidebar,
+ );
+ let budgetName = useSelector(state => state.prefs.local.budgetName);
+
+ let { loadPrefs, closeBudget } = useActions();
+
useEffect(() => {
let unlisten = listen('prefs-updated', () => {
loadPrefs();
@@ -127,11 +128,11 @@ function Settings({
const { isNarrowWidth } = useResponsive();
const themesFlag = useFeatureFlag('themes');
+ useSetThemeColor(colors.n11);
return (
<View
style={{
- marginInline:
- globalPrefs.floatingSidebar && !isNarrowWidth ? 'auto' : 0,
+ marginInline: floatingSidebar && !isNarrowWidth ? 'auto' : 0,
}}
>
<Page
@@ -153,11 +154,7 @@ function Settings({
{/* The only spot to close a budget on mobile */}
<FormField>
<FormLabel title="Budget Name" />
- <Input
- value={prefs.budgetName}
- disabled
- style={{ color: '#999' }}
- />
+ <Input value={budgetName} disabled style={{ color: '#999' }} />
</FormField>
<Button onClick={closeBudget}>Close Budget</Button>
</View>
@@ -165,22 +162,17 @@ function Settings({
<About />
- {!Platform.isBrowser && (
- <GlobalSettings
- globalPrefs={globalPrefs}
- saveGlobalPrefs={saveGlobalPrefs}
- />
- )}
+ {!Platform.isBrowser && <GlobalSettings />}
- {themesFlag && <ThemeSettings saveGlobalPrefs={saveGlobalPrefs} />}
- <FormatSettings prefs={prefs} savePrefs={savePrefs} />
- <EncryptionSettings prefs={prefs} pushModal={pushModal} />
- <ExportBudget prefs={prefs} />
+ {themesFlag && <ThemeSettings />}
+ <FormatSettings />
+ <EncryptionSettings />
+ <ExportBudget />
<AdvancedToggle>
- <AdvancedAbout prefs={prefs} />
+ <AdvancedAbout />
<ResetCache />
- <ResetSync isEnabled={!!prefs.groupId} resetSync={resetSync} />
+ <ResetSync />
<FixSplitsTool />
<ExperimentalFeatures />
</AdvancedToggle>
@@ -189,13 +181,3 @@ function Settings({
</View>
);
}
-
-export default withThemeColor(colors.n11)(
- connect(
- state => ({
- prefs: state.prefs.local,
- globalPrefs: state.prefs.global,
- }),
- actions,
- )(Settings),
-);
diff --git a/packages/desktop-client/src/hooks/index.js b/packages/desktop-client/src/hooks/index.js
deleted file mode 100644
index 8304c4bbf4..0000000000
--- a/packages/desktop-client/src/hooks/index.js
+++ /dev/null
@@ -1,9 +0,0 @@
-import { useEffect } from 'react';
-
-import { setThemeColor } from '../util/withThemeColor';
-
-export function useSetThemeColor(color) {
- useEffect(() => {
- setThemeColor(color);
- }, [color, setThemeColor]);
-}
diff --git a/packages/desktop-client/src/hooks/useActions.ts b/packages/desktop-client/src/hooks/useActions.ts
index 2078a4d8c5..66c2493b57 100644
--- a/packages/desktop-client/src/hooks/useActions.ts
+++ b/packages/desktop-client/src/hooks/useActions.ts
@@ -2,13 +2,26 @@ import { useMemo } from 'react';
import { useDispatch } from 'react-redux';
import { bindActionCreators } from 'redux';
+import { type ThunkAction } from 'redux-thunk';
import * as actions from 'loot-core/src/client/actions';
+import type { Action, State } from 'loot-core/src/client/state-types';
+
+type ActionReturnType<T extends (...args: unknown[]) => unknown> =
+ ReturnType<T> extends ThunkAction<infer ReturnType, State, never, Action>
+ ? ReturnType
+ : ReturnType<T>;
+
+type BoundActions = {
+ [Key in keyof typeof actions]: (
+ ...args: Parameters<(typeof actions)[Key]>
+ ) => ActionReturnType<(typeof actions)[Key]>;
+};
// https://react-redux.js.org/api/hooks#recipe-useactions
export function useActions() {
const dispatch = useDispatch();
return useMemo(() => {
return bindActionCreators(actions, dispatch);
- }, [dispatch]);
+ }, [dispatch]) as unknown as BoundActions;
}
diff --git a/packages/desktop-client/src/hooks/useSetThemeColor.ts b/packages/desktop-client/src/hooks/useSetThemeColor.ts
new file mode 100644
index 0000000000..15509fa7a7
--- /dev/null
+++ b/packages/desktop-client/src/hooks/useSetThemeColor.ts
@@ -0,0 +1,13 @@
+import { useEffect } from 'react';
+
+export function useSetThemeColor(color: string) {
+ useEffect(() => {
+ setThemeColor(color);
+ }, [color]);
+}
+
+function setThemeColor(color: string) {
+ const metaTags = document.getElementsByTagName('meta');
+ const themeTag = [...metaTags].find(tag => tag.name === 'theme-color');
+ themeTag.setAttribute('content', color);
+}
diff --git a/packages/desktop-client/src/util/withThemeColor.tsx b/packages/desktop-client/src/util/withThemeColor.tsx
deleted file mode 100644
index c146b60aae..0000000000
--- a/packages/desktop-client/src/util/withThemeColor.tsx
+++ /dev/null
@@ -1,28 +0,0 @@
-import React, { Component } from 'react';
-
-export const withThemeColor = color => WrappedComponent => {
- class WithThemeColor extends Component {
- static displayName = `withThemeColor(${
- WrappedComponent.displayName || WrappedComponent.name
- })`;
-
- componentDidMount() {
- setThemeColor(color);
- }
-
- componentDidUpdate() {
- setThemeColor(color);
- }
-
- render() {
- return <WrappedComponent {...this.props} />;
- }
- }
- return WithThemeColor;
-};
-
-export function setThemeColor(color) {
- const metaTags = document.getElementsByTagName('meta');
- const themeTag = [...metaTags].find(tag => tag.name === 'theme-color');
- themeTag.setAttribute('content', color);
-}
diff --git a/packages/loot-core/src/client/actions/account.ts b/packages/loot-core/src/client/actions/account.ts
index 311a5cf00a..cecc9d8f3d 100644
--- a/packages/loot-core/src/client/actions/account.ts
+++ b/packages/loot-core/src/client/actions/account.ts
@@ -5,14 +5,19 @@ import type {
AccountSyncStatusAction,
SetAccountsSyncingAction,
} from '../state-types/account';
+import type {
+ MarkAccountReadAction,
+ SetLastTransactionAction,
+ UpdateNewTransactionsAction,
+} from '../state-types/queries';
import { addNotification } from './notifications';
import { getPayees, getAccounts } from './queries';
-import type { ActionResult } from './types';
+import type { Dispatch, GetState } from './types';
export function setAccountsSyncing(
name: SetAccountsSyncingAction['name'],
-): ActionResult {
+): SetAccountsSyncingAction {
return {
type: constants.SET_ACCOUNTS_SYNCING,
name,
@@ -23,7 +28,7 @@ export function markAccountFailed(
id: AccountSyncStatusAction['id'],
errorType?: string,
errorCode?: string,
-): ActionResult {
+): AccountSyncStatusAction {
return {
type: 'ACCOUNT_SYNC_STATUS',
id,
@@ -34,7 +39,7 @@ export function markAccountFailed(
}
export function markAccountSuccess(
id: AccountSyncStatusAction['id'],
-): ActionResult {
+): AccountSyncStatusAction {
return {
type: 'ACCOUNT_SYNC_STATUS',
id,
@@ -43,23 +48,23 @@ export function markAccountSuccess(
}
export function setFailedAccounts(
syncErrors: AccountSyncFailuresAction['syncErrors'],
-): ActionResult {
+): AccountSyncFailuresAction {
return {
- type: 'ACCOUNT_SYNC_FAILURES',
+ type: constants.ACCOUNT_SYNC_FAILURES,
syncErrors,
};
}
-export function unlinkAccount(id: string): ActionResult {
- return async dispatch => {
+export function unlinkAccount(id: string) {
+ return async (dispatch: Dispatch) => {
await send('account-unlink', { id });
dispatch(markAccountSuccess(id));
dispatch(getAccounts());
};
}
-export function linkAccount(requisitionId, account, upgradingId): ActionResult {
- return async dispatch => {
+export function linkAccount(requisitionId, account, upgradingId) {
+ return async (dispatch: Dispatch) => {
await send('gocardless-accounts-link', {
requisitionId,
account,
@@ -70,13 +75,14 @@ export function linkAccount(requisitionId, account, upgradingId): ActionResult {
};
}
+// TODO: type correctly or remove (unused)
export function connectAccounts(
institution,
publicToken,
accountIds,
offbudgetIds,
-): ActionResult {
- return async dispatch => {
+) {
+ return async (dispatch: Dispatch) => {
let ids = await send('accounts-connect', {
institution,
publicToken,
@@ -89,13 +95,14 @@ export function connectAccounts(
};
}
+// TODO: type correctly or remove (unused)
export function connectGoCardlessAccounts(
institution,
publicToken,
accountIds,
offbudgetIds,
-): ActionResult {
- return async dispatch => {
+) {
+ return async (dispatch: Dispatch) => {
let ids = await send('gocardless-accounts-connect', {
institution,
publicToken,
@@ -108,8 +115,8 @@ export function connectGoCardlessAccounts(
};
}
-export function syncAccounts(id): ActionResult {
- return async (dispatch, getState) => {
+export function syncAccounts(id: string) {
+ return async (dispatch: Dispatch, getState: GetState) => {
if (getState().account.accountsSyncing) {
return false;
}
@@ -182,15 +189,17 @@ export function syncAccounts(id): ActionResult {
}
// Remember the last transaction manually added to the system
-export function setLastTransaction(transaction): ActionResult {
+export function setLastTransaction(
+ transaction: SetLastTransactionAction['transaction'],
+): SetLastTransactionAction {
return {
type: constants.SET_LAST_TRANSACTION,
transaction,
};
}
-export function parseTransactions(filepath, options): ActionResult {
- return async dispatch => {
+export function parseTransactions(filepath, options) {
+ return async (dispatch: Dispatch) => {
return await send('transactions-parse-file', {
filepath,
options,
@@ -198,8 +207,8 @@ export function parseTransactions(filepath, options): ActionResult {
};
}
-export function importTransactions(id, transactions): ActionResult {
- return async dispatch => {
+export function importTransactions(id, transactions) {
+ return async (dispatch: Dispatch) => {
let {
errors = [],
added,
@@ -229,14 +238,14 @@ export function importTransactions(id, transactions): ActionResult {
};
}
-export function updateNewTransactions(changedId): ActionResult {
+export function updateNewTransactions(changedId): UpdateNewTransactionsAction {
return {
type: constants.UPDATE_NEW_TRANSACTIONS,
changedId,
};
}
-export function markAccountRead(accountId): ActionResult {
+export function markAccountRead(accountId): MarkAccountReadAction {
return {
type: constants.MARK_ACCOUNT_READ,
accountId: accountId,
diff --git a/packages/loot-core/src/client/actions/app.ts b/packages/loot-core/src/client/actions/app.ts
index 05d4476acb..dac6c7bb5c 100644
--- a/packages/loot-core/src/client/actions/app.ts
+++ b/packages/loot-core/src/client/actions/app.ts
@@ -1,18 +1,22 @@
import { send } from '../../platform/client/fetch';
import * as constants from '../constants';
-import type { AppState, SetLastUndoStateAction } from '../state-types/app';
+import type {
+ AppState,
+ SetAppStateAction,
+ SetLastUndoStateAction,
+} from '../state-types/app';
-import type { ActionResult } from './types';
+import type { Dispatch } from './types';
-export function setAppState(state: Partial<AppState>): ActionResult {
+export function setAppState(state: Partial<AppState>): SetAppStateAction {
return {
type: constants.SET_APP_STATE,
state,
};
}
-export function updateApp(): ActionResult {
- return async dispatch => {
+export function updateApp() {
+ return async (dispatch: Dispatch) => {
global.Actual.applyAppUpdate();
dispatch(setAppState({ updateInfo: null }));
};
@@ -20,7 +24,7 @@ export function updateApp(): ActionResult {
export function setLastUndoState(
undoState: SetLastUndoStateAction['undoState'],
-): ActionResult {
+): SetLastUndoStateAction {
return {
type: constants.SET_LAST_UNDO_STATE,
undoState,
@@ -30,17 +34,14 @@ export function setLastUndoState(
// This is only used in the fake web version where everything runs in
// the browser. It's a way to send a file to the backend to be
// imported into the virtual filesystem.
-export function uploadFile(
- filename: string,
- contents: ArrayBuffer,
-): ActionResult {
- return dispatch => {
+export function uploadFile(filename: string, contents: ArrayBuffer) {
+ return () => {
return send('upload-file-web', { filename, contents });
};
}
-export function focused(): ActionResult {
- return dispatch => {
+export function focused() {
+ return () => {
return send('app-focused');
};
}
diff --git a/packages/loot-core/src/client/actions/backups.ts b/packages/loot-core/src/client/actions/backups.ts
index e36f872e14..10571fcfbf 100644
--- a/packages/loot-core/src/client/actions/backups.ts
+++ b/packages/loot-core/src/client/actions/backups.ts
@@ -1,12 +1,12 @@
import { send } from '../../platform/client/fetch';
import { closeBudget, loadBudget } from './budgets';
-import type { ActionResult } from './types';
+import type { Dispatch, GetState } from './types';
// Take in the budget id so that backups can be loaded when a budget
// isn't opened
-export function loadBackup(budgetId, backupId): ActionResult {
- return async (dispatch, getState) => {
+export function loadBackup(budgetId, backupId) {
+ return async (dispatch: Dispatch, getState: GetState) => {
const prefs = getState().prefs.local;
if (prefs && prefs.id) {
await dispatch(closeBudget());
@@ -17,8 +17,8 @@ export function loadBackup(budgetId, backupId): ActionResult {
};
}
-export function makeBackup(): ActionResult {
- return async (dispatch, getState) => {
+export function makeBackup() {
+ return async (dispatch: Dispatch, getState: GetState) => {
const prefs = getState().prefs.local;
if (prefs && prefs.id) {
await send('backup-make', { id: prefs.id });
diff --git a/packages/loot-core/src/client/actions/budgets.ts b/packages/loot-core/src/client/actions/budgets.ts
index d9a54920cd..97e2673ca6 100644
--- a/packages/loot-core/src/client/actions/budgets.ts
+++ b/packages/loot-core/src/client/actions/budgets.ts
@@ -6,10 +6,10 @@ import * as constants from '../constants';
import { setAppState } from './app';
import { closeModal, pushModal } from './modals';
import { loadPrefs, loadGlobalPrefs } from './prefs';
-import type { ActionResult } from './types';
+import type { Dispatch, GetState } from './types';
-export function updateStatusText(text: string | null): ActionResult {
- return (dispatch, getState) => {
+export function updateStatusText(text: string | null) {
+ return (dispatch: Dispatch, getState: GetState) => {
const { loadingText } = getState().app;
// The presence of any loading text puts the app in a "loading"
// state. We only ever want to update the text, we never want to
@@ -21,8 +21,8 @@ export function updateStatusText(text: string | null): ActionResult {
};
}
-export function loadBudgets(): ActionResult {
- return async dispatch => {
+export function loadBudgets() {
+ return async (dispatch: Dispatch) => {
const budgets = await send('get-budgets');
dispatch({
@@ -32,8 +32,8 @@ export function loadBudgets(): ActionResult {
};
}
-export function loadRemoteFiles(): ActionResult {
- return async dispatch => {
+export function loadRemoteFiles() {
+ return async (dispatch: Dispatch) => {
const files = await send('get-remote-files');
dispatch({
@@ -43,8 +43,8 @@ export function loadRemoteFiles(): ActionResult {
};
}
-export function loadAllFiles(): ActionResult {
- return async (dispatch, getState) => {
+export function loadAllFiles() {
+ return async (dispatch: Dispatch, getState: GetState) => {
const budgets = await send('get-budgets');
const files = await send('get-remote-files');
@@ -58,12 +58,8 @@ export function loadAllFiles(): ActionResult {
};
}
-export function loadBudget(
- id: string,
- loadingText = '',
- options = {},
-): ActionResult {
- return async (dispatch, getState) => {
+export function loadBudget(id: string, loadingText = '', options = {}) {
+ return async (dispatch: Dispatch) => {
dispatch(setAppState({ loadingText }));
// Loading a budget may fail
@@ -102,8 +98,8 @@ export function loadBudget(
};
}
-export function closeBudget(): ActionResult {
- return async (dispatch, getState) => {
+export function closeBudget() {
+ return async (dispatch: Dispatch, getState: GetState) => {
const prefs = getState().prefs.local;
if (prefs && prefs.id) {
// This clears out all the app state so the user starts fresh
@@ -119,8 +115,8 @@ export function closeBudget(): ActionResult {
};
}
-export function closeBudgetUI(): ActionResult {
- return async (dispatch, getState) => {
+export function closeBudgetUI() {
+ return async (dispatch: Dispatch, getState: GetState) => {
let prefs = getState().prefs.local;
if (prefs && prefs.id) {
dispatch({ type: constants.CLOSE_BUDGET });
@@ -131,18 +127,15 @@ export function closeBudgetUI(): ActionResult {
export function deleteBudget(
id: string | undefined,
cloudFileId: string | undefined,
-): ActionResult {
- return async dispatch => {
+) {
+ return async (dispatch: Dispatch) => {
await send('delete-budget', { id, cloudFileId });
await dispatch(loadAllFiles());
};
}
-export function createBudget({
- testMode = false,
- demoMode = false,
-} = {}): ActionResult {
- return async (dispatch, getState) => {
+export function createBudget({ testMode = false, demoMode = false } = {}) {
+ return async (dispatch: Dispatch) => {
dispatch(
setAppState({
loadingText: testMode || demoMode ? 'Making demo...' : '',
@@ -169,8 +162,8 @@ export function createBudget({
export function importBudget(
filepath: string,
type: Parameters<Handlers['import-budget']>[0]['type'],
-): ActionResult {
- return async (dispatch, getState) => {
+) {
+ return async (dispatch: Dispatch) => {
const { error } = await send('import-budget', { filepath, type });
if (error) {
throw new Error(error);
@@ -183,8 +176,8 @@ export function importBudget(
};
}
-export function uploadBudget(id: string): ActionResult {
- return async dispatch => {
+export function uploadBudget(id: string) {
+ return async (dispatch: Dispatch) => {
let { error } = await send('upload-budget', { id });
if (error) {
return { error };
@@ -195,8 +188,8 @@ export function uploadBudget(id: string): ActionResult {
};
}
-export function closeAndDownloadBudget(cloudFileId: string): ActionResult {
- return async dispatch => {
+export function closeAndDownloadBudget(cloudFileId: string) {
+ return async (dispatch: Dispatch) => {
// It's very important that we set this loading message before
// closing the budget. Otherwise, the manager will ignore our
// loading message and clear it when it loads, showing the file
@@ -207,11 +200,8 @@ export function closeAndDownloadBudget(cloudFileId: string): ActionResult {
};
}
-export function downloadBudget(
- cloudFileId: string,
- { replace = false } = {},
-): ActionResult {
- return async dispatch => {
+export function downloadBudget(cloudFileId: string, { replace = false } = {}) {
+ return async (dispatch: Dispatch) => {
dispatch(setAppState({ loadingText: 'Downloading...' }));
let { id, error } = await send('download-budget', {
diff --git a/packages/loot-core/src/client/actions/modals.ts b/packages/loot-core/src/client/actions/modals.ts
index 87c1abb1bb..bcb71af529 100644
--- a/packages/loot-core/src/client/actions/modals.ts
+++ b/packages/loot-core/src/client/actions/modals.ts
@@ -1,12 +1,16 @@
import * as constants from '../constants';
-import type { Modal } from '../state-types/modals';
-
-import type { ActionResult } from './types';
+import type {
+ CloseModalAction,
+ Modal,
+ PopModalAction,
+ PushModalAction,
+ ReplaceModalAction,
+} from '../state-types/modals';
export function pushModal<M extends Modal>(
name: M['name'],
options: M['options'],
-): ActionResult {
+): PushModalAction {
// @ts-expect-error TS is unable to determine that `name` and `options` match
let modal: M = { name, options };
return { type: constants.PUSH_MODAL, modal };
@@ -15,16 +19,16 @@ export function pushModal<M extends Modal>(
export function replaceModal<M extends Modal>(
name: M['name'],
options: M['options'],
-): ActionResult {
+): ReplaceModalAction {
// @ts-expect-error TS is unable to determine that `name` and `options` match
let modal: M = { name, options };
return { type: constants.REPLACE_MODAL, modal };
}
-export function popModal(): ActionResult {
+export function popModal(): PopModalAction {
return { type: constants.POP_MODAL };
}
-export function closeModal(): ActionResult {
+export function closeModal(): CloseModalAction {
return { type: constants.CLOSE_MODAL };
}
diff --git a/packages/loot-core/src/client/actions/notifications.ts b/packages/loot-core/src/client/actions/notifications.ts
index ca3cd6964f..a2f2582564 100644
--- a/packages/loot-core/src/client/actions/notifications.ts
+++ b/packages/loot-core/src/client/actions/notifications.ts
@@ -1,13 +1,15 @@
import { v4 as uuidv4 } from 'uuid';
import * as constants from '../constants';
-import { type Notification } from '../state-types/notifications';
-
-import type { ActionResult } from './types';
+import type {
+ AddNotificationAction,
+ RemoveNotificationAction,
+ Notification,
+} from '../state-types/notifications';
export function addNotification(
notification: Omit<Notification, 'id'> & { id?: string },
-): ActionResult {
+): AddNotificationAction {
return {
type: constants.ADD_NOTIFICATION,
notification: {
@@ -17,7 +19,7 @@ export function addNotification(
};
}
-export function addGenericErrorNotification(): ActionResult {
+export function addGenericErrorNotification() {
return addNotification({
type: 'error',
message:
@@ -26,7 +28,7 @@ export function addGenericErrorNotification(): ActionResult {
});
}
-export function removeNotification(id: string): ActionResult {
+export function removeNotification(id: string): RemoveNotificationAction {
return {
type: constants.REMOVE_NOTIFICATION,
id,
diff --git a/packages/loot-core/src/client/actions/prefs.ts b/packages/loot-core/src/client/actions/prefs.ts
index c6ca850f2e..3521e89aef 100644
--- a/packages/loot-core/src/client/actions/prefs.ts
+++ b/packages/loot-core/src/client/actions/prefs.ts
@@ -2,10 +2,10 @@ import { send } from '../../platform/client/fetch';
import * as constants from '../constants';
import { closeModal } from './modals';
-import type { ActionResult } from './types';
+import type { Dispatch, GetState } from './types';
-export function loadPrefs(): ActionResult {
- return async (dispatch, getState) => {
+export function loadPrefs() {
+ return async (dispatch: Dispatch, getState: GetState) => {
let prefs = await send('load-prefs');
// Remove any modal state if switching between budgets
@@ -24,8 +24,8 @@ export function loadPrefs(): ActionResult {
};
}
-export function savePrefs(prefs): ActionResult {
- return async dispatch => {
+export function savePrefs(prefs) {
+ return async (dispatch: Dispatch) => {
await send('save-prefs', prefs);
dispatch({
type: constants.MERGE_LOCAL_PREFS,
@@ -34,8 +34,8 @@ export function savePrefs(prefs): ActionResult {
};
}
-export function loadGlobalPrefs(): ActionResult {
- return async (dispatch, getState) => {
+export function loadGlobalPrefs() {
+ return async (dispatch: Dispatch, getState: GetState) => {
let globalPrefs = await send('load-global-prefs');
dispatch({
type: constants.SET_PREFS,
@@ -46,8 +46,8 @@ export function loadGlobalPrefs(): ActionResult {
};
}
-export function saveGlobalPrefs(prefs): ActionResult {
- return async dispatch => {
+export function saveGlobalPrefs(prefs) {
+ return async (dispatch: Dispatch) => {
await send('save-global-prefs', prefs);
dispatch({
type: constants.MERGE_GLOBAL_PREFS,
diff --git a/packages/loot-core/src/client/actions/queries.ts b/packages/loot-core/src/client/actions/queries.ts
index 1b9b18cc35..5631fcbdea 100644
--- a/packages/loot-core/src/client/actions/queries.ts
+++ b/packages/loot-core/src/client/actions/queries.ts
@@ -5,10 +5,10 @@ import * as constants from '../constants';
import { pushModal } from './modals';
import { addNotification, addGenericErrorNotification } from './notifications';
-import type { ActionResult } from './types';
+import type { Dispatch, GetState } from './types';
export function applyBudgetAction(month, type, args) {
- return async function (dispatch) {
+ return async (dispatch: Dispatch) => {
switch (type) {
case 'budget-amount':
await send('budget/budget-amount', {
@@ -119,8 +119,8 @@ export function applyBudgetAction(month, type, args) {
};
}
-export function getCategories(): ActionResult {
- return async function (dispatch) {
+export function getCategories() {
+ return async (dispatch: Dispatch) => {
const categories = await send('get-categories');
dispatch({
type: constants.LOAD_CATEGORIES,
@@ -134,8 +134,8 @@ export function createCategory(
name: string,
groupId: string,
isIncome: boolean,
-): ActionResult {
- return async function (dispatch) {
+) {
+ return async (dispatch: Dispatch) => {
let id = await send('category-create', {
name,
groupId,
@@ -146,8 +146,8 @@ export function createCategory(
};
}
-export function deleteCategory(id: string, transferId?: string): ActionResult {
- return async function (dispatch, getState) {
+export function deleteCategory(id: string, transferId?: string) {
+ return async (dispatch: Dispatch) => {
let { error } = await send('category-delete', { id, transferId });
if (error) {
@@ -175,36 +175,36 @@ export function deleteCategory(id: string, transferId?: string): ActionResult {
};
}
-export function updateCategory(category): ActionResult {
- return async dispatch => {
+export function updateCategory(category) {
+ return async (dispatch: Dispatch) => {
await send('category-update', category);
dispatch(getCategories());
};
}
-export function moveCategory(id, groupId, targetId): ActionResult {
- return async (dispatch, getState) => {
+export function moveCategory(id, groupId, targetId) {
+ return async (dispatch: Dispatch) => {
await send('category-move', { id, groupId, targetId });
await dispatch(getCategories());
};
}
-export function moveCategoryGroup(id, targetId): ActionResult {
- return async dispatch => {
+export function moveCategoryGroup(id, targetId) {
+ return async (dispatch: Dispatch) => {
await send('category-group-move', { id, targetId });
await dispatch(getCategories());
};
}
-export function createGroup(name): ActionResult {
- return async dispatch => {
+export function createGroup(name) {
+ return async (dispatch: Dispatch) => {
let id = await send('category-group-create', { name });
dispatch(getCategories());
return id;
};
}
-export function updateGroup(group): ActionResult {
+export function updateGroup(group) {
// 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
@@ -216,7 +216,7 @@ export function updateGroup(group): ActionResult {
};
}
-export function deleteGroup(id, transferId): ActionResult {
+export function deleteGroup(id, transferId) {
return async function (dispatch, getState) {
await send('category-group-delete', { id, transferId });
await dispatch(getCategories());
@@ -225,8 +225,8 @@ export function deleteGroup(id, transferId): ActionResult {
};
}
-export function getPayees(): ActionResult {
- return async function (dispatch) {
+export function getPayees() {
+ return async (dispatch: Dispatch) => {
let payees = await send('payees-get');
dispatch({
type: constants.LOAD_PAYEES,
@@ -236,37 +236,37 @@ export function getPayees(): ActionResult {
};
}
-export function initiallyLoadPayees(): ActionResult {
- return async function (dispatch, getState) {
+export function initiallyLoadPayees() {
+ return async (dispatch: Dispatch, getState: GetState) => {
if (getState().queries.payees.length === 0) {
return dispatch(getPayees());
}
};
}
-export function createPayee(name: string): ActionResult {
- return async dispatch => {
+export function createPayee(name: string) {
+ return async () => {
return send('payee-create', { name: name.trim() });
};
}
-export function getAccounts(): ActionResult {
- return async function (dispatch) {
+export function getAccounts() {
+ return async (dispatch: Dispatch) => {
const accounts = await send('accounts-get');
dispatch({ type: constants.LOAD_ACCOUNTS, accounts });
return accounts;
};
}
-export function updateAccount(account): ActionResult {
- return async function (dispatch) {
+export function updateAccount(account) {
+ return async (dispatch: Dispatch) => {
dispatch({ type: constants.UPDATE_ACCOUNT, account });
await send('account-update', account);
};
}
-export function createAccount(name, balance, offBudget): ActionResult {
- return async function (dispatch) {
+export function createAccount(name, balance, offBudget) {
+ return async (dispatch: Dispatch) => {
let id = await send('account-create', { name, balance, offBudget });
await dispatch(getAccounts());
await dispatch(getPayees());
@@ -274,8 +274,8 @@ export function createAccount(name, balance, offBudget): ActionResult {
};
}
-export function openAccountCloseModal(accountId): ActionResult {
- return async function (dispatch, getState) {
+export function openAccountCloseModal(accountId) {
+ return async (dispatch: Dispatch, getState: GetState) => {
const { balance, numTransactions } = await send('account-properties', {
id: accountId,
});
@@ -293,13 +293,8 @@ export function openAccountCloseModal(accountId): ActionResult {
};
}
-export function closeAccount(
- accountId,
- transferAccountId,
- categoryId,
- forced,
-): ActionResult {
- return async function (dispatch) {
+export function closeAccount(accountId, transferAccountId, categoryId, forced) {
+ return async (dispatch: Dispatch) => {
await send('account-close', {
id: accountId,
transferAccountId,
@@ -310,14 +305,14 @@ export function closeAccount(
};
}
-export function reopenAccount(accountId): ActionResult {
- return async function (dispatch) {
+export function reopenAccount(accountId) {
+ return async (dispatch: Dispatch) => {
await send('account-reopen', { id: accountId });
dispatch(getAccounts());
};
}
-export function forceCloseAccount(accountId): ActionResult {
+export function forceCloseAccount(accountId) {
return closeAccount(accountId, null, null, true);
}
diff --git a/packages/loot-core/src/client/actions/sync.ts b/packages/loot-core/src/client/actions/sync.ts
index 6c95ea3e86..4838c1e438 100644
--- a/packages/loot-core/src/client/actions/sync.ts
+++ b/packages/loot-core/src/client/actions/sync.ts
@@ -4,9 +4,10 @@ import { getUploadError } from '../../shared/errors';
import { syncAccounts } from './account';
import { pushModal } from './modals';
import { loadPrefs } from './prefs';
+import type { Dispatch, GetState } from './types';
export function resetSync() {
- return async (dispatch, getState) => {
+ return async (dispatch: Dispatch) => {
let { error } = await send('sync-reset');
if (error) {
@@ -36,7 +37,7 @@ export function resetSync() {
}
export function sync() {
- return async (dispatch, getState) => {
+ return async (dispatch: Dispatch, getState: GetState) => {
const prefs = getState().prefs.local;
if (prefs && prefs.id) {
let result = await send('sync');
@@ -49,7 +50,7 @@ export function sync() {
}
export function syncAndDownload(accountId) {
- return async (dispatch, getState) => {
+ return async (dispatch: Dispatch) => {
// It is *critical* that we sync first because of transaction
// reconciliation. We want to get all transactions that other
// clients have already made, so that imported transactions can be
@@ -73,6 +74,6 @@ export function syncAndDownload(accountId) {
// updates
return true;
}
- return { hasUpdated: hasDownloaded || syncState.updated };
+ return { hasUpdated: hasDownloaded };
};
}
diff --git a/packages/loot-core/src/client/actions/types.d.ts b/packages/loot-core/src/client/actions/types.d.ts
index 86aff269f1..ad9e5ee358 100644
--- a/packages/loot-core/src/client/actions/types.d.ts
+++ b/packages/loot-core/src/client/actions/types.d.ts
@@ -1,7 +1,6 @@
import type { ThunkDispatch } from 'redux-thunk';
-import type { Action, State } from '../state-types';
+import type { State, Action } from '../state-types';
-export type ActionResult = Parameters<
- ThunkDispatch<State, Record<string, never>, Action>
->[0];
+export type Dispatch = ThunkDispatch<State, never, Action>;
+export type GetState = () => State;
diff --git a/packages/loot-core/src/client/actions/user.ts b/packages/loot-core/src/client/actions/user.ts
index accdd2b413..6084b4e548 100644
--- a/packages/loot-core/src/client/actions/user.ts
+++ b/packages/loot-core/src/client/actions/user.ts
@@ -3,9 +3,10 @@ import * as constants from '../constants';
import { loadAllFiles, closeBudget } from './budgets';
import { loadGlobalPrefs } from './prefs';
+import type { Dispatch } from './types';
export function getUserData() {
- return async dispatch => {
+ return async (dispatch: Dispatch) => {
const data = await send('subscribe-get-user');
dispatch({
@@ -17,7 +18,7 @@ export function getUserData() {
}
export function loggedIn() {
- return async dispatch => {
+ return async (dispatch: Dispatch) => {
await dispatch(getUserData());
// We want to be careful about how we call loadAllFiles. It will
@@ -39,7 +40,7 @@ export function loggedIn() {
}
export function signOut() {
- return async dispatch => {
+ return async (dispatch: Dispatch) => {
await send('subscribe-sign-out');
dispatch(getUserData());
diff --git a/upcoming-release-notes/1404.md b/upcoming-release-notes/1404.md
new file mode 100644
index 0000000000..19a7cbae47
--- /dev/null
+++ b/upcoming-release-notes/1404.md
@@ -0,0 +1,6 @@
+---
+category: Maintenance
+authors: [j-f1]
+---
+
+Improve TypeScript compatibility with Redux-related code