Skip to content

Commit

Permalink
fix: Sync Account on Add (#1104)
Browse files Browse the repository at this point in the history
* fix: Sync Account on Add

Added subscription for accounts store

* Safety
  • Loading branch information
alexrisch authored Oct 25, 2024
1 parent f0756cf commit d5ab467
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion components/XmtpEngine.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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);
});
Expand All @@ -143,6 +164,7 @@ class XmtpEngine {

destroy() {
logger.debug("[XmtpEngine] Removing subscriptions");
this.accountsStoreSubscription?.();
this.appStoreSubscription?.();
this.appStateSubscription?.remove();
}
Expand Down

0 comments on commit d5ab467

Please sign in to comment.