From d5ab467bf720df4862562a8ff51ddf22c321f0ee Mon Sep 17 00:00:00 2001 From: Alex Risch Date: Fri, 25 Oct 2024 13:19:14 -0400 Subject: [PATCH] fix: Sync Account on Add (#1104) * fix: Sync Account on Add Added subscription for accounts store * Safety --- components/XmtpEngine.tsx | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/components/XmtpEngine.tsx b/components/XmtpEngine.tsx index fbdb2324f..5010abdf7 100644 --- a/components/XmtpEngine.tsx +++ b/components/XmtpEngine.tsx @@ -12,7 +12,11 @@ import { } from "react-native"; import { getExistingDataSource } from "../data/db/datasource"; -import { getAccountsList, getChatStore } from "../data/store/accountsStore"; +import { + getAccountsList, + getChatStore, + useAccountsStore, +} from "../data/store/accountsStore"; import { useAppStore } from "../data/store/appStore"; import { getTopicsData } from "../utils/api"; import { loadSavedNotificationMessagesToContext } from "../utils/notifications"; @@ -25,6 +29,7 @@ import { sendPendingMessages } from "../utils/xmtpRN/send"; import { syncXmtpClient } from "../utils/xmtpRN/sync"; class XmtpEngine { + accountsStoreSubscription: (() => void) | null = null; appStoreSubscription: (() => void) | null = null; appStateSubscription: NativeEventSubscription | null = null; isInternetReachable: boolean = false; @@ -47,6 +52,21 @@ class XmtpEngine { const { isInternetReachable, hydrationDone } = useAppStore.getState(); this.isInternetReachable = isInternetReachable; this.hydrationDone = hydrationDone; + this.accountsStoreSubscription = useAccountsStore.subscribe( + (state, previousState) => { + if (!previousState?.accounts || !state?.accounts) return; + if (previousState.accounts !== state.accounts) { + const previousAccounts = new Set(previousState.accounts); + const newAccounts = new Set(state.accounts); + const accountsToSync = [...newAccounts].filter( + (account) => !previousAccounts.has(account) + ); + if (accountsToSync.length > 0) { + this.syncAccounts(accountsToSync); + } + } + } + ); this.appStoreSubscription = useAppStore.subscribe( (state, previousState) => { this.isInternetReachable = state.isInternetReachable; @@ -125,6 +145,7 @@ class XmtpEngine { async syncAccounts(accountsToSync: string[]) { accountsToSync.forEach((a) => { if (!this.syncingAccounts[a]) { + logger.info(`[XmtpEngine] Syncing account ${a}`); getTopicsData(a).then((topicsData) => { getChatStore(a).getState().setTopicsData(topicsData, true); }); @@ -143,6 +164,7 @@ class XmtpEngine { destroy() { logger.debug("[XmtpEngine] Removing subscriptions"); + this.accountsStoreSubscription?.(); this.appStoreSubscription?.(); this.appStateSubscription?.remove(); }