mobx#reaction JavaScript Examples

The following examples show how to use mobx#reaction. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WalletLoader.js    From apps-ng with Apache License 2.0 6 votes vote down vote up
StoreInjector = (({ children }) => {
  const appStore = useStore()
  const [shouldRenderContent, setShouldRenderContent] = useState(false)

  useEffect(() => {
    if (!appStore || !appStore.appRuntime) {
      return
    }
    if (typeof appStore.wallet !== 'undefined') {
      return
    }
    appStore.wallet = createWalletStore({
      appSettings: appStore.settings,
      appAccount: appStore.account,
      appRuntime: appStore.appRuntime
    })
  }, [appStore])

  useEffect(
    () =>
      reaction(
        () => appStore.wallet,
        () => {
          if (appStore.wallet && !shouldRenderContent) {
            setShouldRenderContent(true)
          }
        },
        { fireImmediately: true }),
    []
  )

  return shouldRenderContent ? children : null
})
Example #2
Source File: MultiSigAccount.js    From RRWallet with MIT License 6 votes vote down vote up
constructor(obj = {}) {
    const { wallets } = obj;
    super(obj);
    this.wallets = (wallets && wallets.map(wallet => new BTCMultiSigWallet(wallet))) || [];
    reaction(
      () => this.wallets.length,
      length => {
        AccountStorage.update();
      }
    );
  }
Example #3
Source File: CoinStore.js    From RRWallet with MIT License 6 votes vote down vote up
async start() {
    try {
      const ret = await storage.load({ key: COINSTORE_PRICE_STORAGE_KEY });
      ret && ret.forEach(el => (el[0] ? this.map.set(el[0], new CoinPrice(el[1])) : null));
    } catch (error) {}

    try {
      const currency = await storage.load({ key: COINSTORE_CURRENCY_STORAGE_KEY });
      this.currency = currency || CURRENCY_TYPE_CNY;
    } catch (error) {
    } finally {
      reaction(
        () => this.currency,
        currency => {
          storage.save({
            key: COINSTORE_CURRENCY_STORAGE_KEY,
            data: currency,
          });
        }
      );
    }

    this.fetchPrice();

    setInterval(async () => {
      try {
        await this.fetchPrice();
      } catch (error) {}
    }, 2 * 60 * 1000);
  }
Example #4
Source File: Wallet.js    From RRWallet with MIT License 6 votes vote down vote up
startObserve() {
    reaction(
      () => this.assetPrice,
      assetPrice => {
        this.save(-2);
      }
    );
    reaction(
      () => this.coins.map(coin => coin.balance),
      () => {
        this.save(-2);
      }
    );
  }
Example #5
Source File: RuntimeLoader.js    From apps-ng with Apache License 2.0 5 votes vote down vote up
StoreInjector = observer(({ children }) => {
  const [shouldInitRuntime, setShouldInitRuntime] = useState(false)

  const appStore = useStore()
  window.__store = appStore

  const keypair = appStore.account?.keypair
  const locked = appStore.account?.locked
  const address = appStore.account?.address

  useEffect(() => {
    if (locked) {
      setShouldInitRuntime(false)
      appStore.appRuntime = undefined
    }
  }, [address, locked])

  useEffect(() => {
    if (!appStore) {
      return
    }
    if (!(!locked && address)) {
      return
    }
    if (shouldInitRuntime) {
      return
    }

    appStore.appRuntime = createAppRuntimeStore({
      appSettings: appStore.settings,
      appAccount: appStore.account
    })
  }, [address, locked, appStore, shouldInitRuntime])

  useEffect(
    () => {
      if (!appStore?.appRuntime) {
        return
      }

      reaction(
        () => appStore.appRuntime,
        () => {
          if (appStore.appRuntime && !shouldInitRuntime) {
            setShouldInitRuntime(true)
          }
        },
        { fireImmediately: true })
    },
    [appStore?.appRuntime]
  )

  return shouldInitRuntime ? <RuntimeInit /> : null
})
Example #6
Source File: RuntimeLoader.js    From apps-ng with Apache License 2.0 5 votes vote down vote up
RuntimeInit = observer(({ children }) => {
  const appStore = useStore()
  const { settings, appRuntime } = appStore

  React.useEffect(() => {
    appRuntime.initEcdhChannel()
  }, [])

  useEffect(
    () =>
      reaction(
        () => settings.phalaTeeApiUrl,
        () => {
          appRuntime.resetNetwork()
        }),
    []
  )

  useEffect(
    () =>
      autorun(
        () => {
          if (!(appRuntime.ecdhShouldJoin && appRuntime.ecdhChannel && appRuntime.info?.ecdhPublicKey)) {
            return
          }
          appRuntime.joinEcdhChannel()
        }),
    []
  )

  useEffect(
    () =>
      autorun(
        () => {
          if (!(settings.phalaTeeApiUrl && appRuntime.ecdhChannel)) {
            return
          }
          appRuntime.initPApi(settings.phalaTeeApiUrl)
        }),
    []
  )

  return <>
    <RuntimeLifecycle />
    {children}
  </>
})
Example #7
Source File: CurrentInfoButton.js    From apps-ng with Apache License 2.0 5 votes vote down vote up
CurrentInfoButton = () => {
  const { isApiConnected, isApiReady } = useApi()
  const unlockedModal = useModal()
  const lockedModal = useModal(true)

  const { account } = useStore()
  const { locked, address } = account

  useEffect(() => {
    if (!isApiReady || !isApiConnected) { return }

    return reaction(
      () => account.address,
      address => {
        account.setKeypair(address)
      },
      { fireImmediately: true }
    )
  }, [isApiReady, isApiConnected])

  const { t } = useTranslation()

  if (!isApiReady || !isApiConnected) {
    return <NavBarButtonWrapper>
      <LoadingWrapper>
        <Loading />
      </LoadingWrapper>
    </NavBarButtonWrapper>
  }

  return <>
    <UnlockedModal {...unlockedModal} />
    <LockedModal {...lockedModal} />
    {locked
      ? <NavBarButtonWrapper onClick={() => lockedModal.setVisible(true)}>
        <LockIcon size={21} />
        <NavBarButtonLabel>{t('Locked')}</NavBarButtonLabel>
      </NavBarButtonWrapper>
      : <NavBarButtonWrapper onClick={() => unlockedModal.setVisible(true)}>
        <UnlockIcon size={21} />
        <NavBarButtonLabel>
          <AccountName address={address} />
        </NavBarButtonLabel>
        {/* todo */}
      </NavBarButtonWrapper>}

  </>
}
Example #8
Source File: HDAccount.js    From RRWallet with MIT License 5 votes vote down vote up
constructor(obj = {}) {
    super(obj);
    if (_.isPlainObject(obj.BTCWallet)) {
      this.BTCWallet = new BTCWallet(obj.BTCWallet);
    }
    if (_.isPlainObject(obj.ETHWallet)) {
      this.ETHWallet = new ETHWallet(obj.ETHWallet);
    }
    if (_.isPlainObject(obj.ETCWallet)) {
      this.ETCWallet = new ETCWallet(obj.ETCWallet);
    } else if (this.ETHWallet) {
      this.ETCWallet = new ETCWallet({
        id: this.ETHWallet.id,
        address: this.ETHWallet.address,
      });
    }
    if (_.isPlainObject(obj.BCHWallet)) {
      this.BCHWallet = new BCHWallet(obj.BCHWallet);
    }

    if (_.isPlainObject(obj.BSVWallet)) {
      this.BSVWallet = new BSVWallet(obj.BSVWallet);
    }
    if (obj.hasOwnProperty("hasBackup")) {
      this.hasBackup = obj.hasBackup;
    }
    this.hdId = obj.hdId;
    this.wallets = _.compact([this.BTCWallet, this.ETHWallet, this.ETCWallet, this.BCHWallet, this.BSVWallet]);

    this.stashedTransferCoinID = obj.stashedTransferCoinID;
    this.stashedReceiveCoinID = obj.stashedReceiveCoinID;
    this.stashedWalletID = obj.stashedWalletID;
    this.isExtendedPublicKeyUploaded = obj.isExtendedPublicKeyUploaded;
    reaction(
      () => this.hasBackup,
      hasBackup => {
        AccountStorage.update();
      }
    );
    reaction(
      () => this.stashedTransferCoinID,
      coinID => {
        AccountStorage.update();
      }
    );
    reaction(
      () => this.stashedReceiveCoinID,
      coinID => {
        AccountStorage.update();
      }
    );
  }
Example #9
Source File: UnlockPasswordSettingScreen.js    From RRWallet with MIT License 5 votes vote down vote up
componentDidMount() {
    reaction(
      () => this.step,
      setp => {
        this.input.clear();
      }
    );
  }
Example #10
Source File: SyncManager.js    From lens-extension-cc with MIT License 4 votes vote down vote up
/**
   * @param {Object} params
   * @param {LensExtension} params.extension Extension instance.
   * @param {Array<CatalogEntity>} params.catalogSource Registered Lens Catalog source.
   * @param {IpcMain} params.ipcMain Singleton instance for sending/receiving messages
   *  to/from Renderer.
   * @constructor
   */
  constructor({ extension, catalogSource, ipcMain }) {
    super();

    let _dataClouds = {};
    let _baseKubeConfigPath = null;

    /**
     * @readonly
     * @member {{ [index: string]: DataCloud }} dataClouds Map of Cloud URL to
     *  DataCloud instance.
     *
     *  __READONLY__: Assign/delete properties on the object, but don't set the entire
     *   property as a whole.
     */
    Object.defineProperty(this, 'dataClouds', {
      enumerable: true,
      get() {
        return _dataClouds;
      },
    });

    /**
     * @member {string|null} baseKubeConfigPath Base path for generated cluster kubeconfig
     *  files. `null` until determined. Does not end with a slash.
     */
    Object.defineProperty(this, 'baseKubeConfigPath', {
      enumerable: true,
      get() {
        return _baseKubeConfigPath;
      },
      set(newValue) {
        if (newValue !== _baseKubeConfigPath) {
          DEV_ENV &&
            rtv.verify(
              { baseKubeConfigPath: newValue },
              { baseKubeConfigPath: [rtv.STRING, (v) => !v.endsWith('/')] }
            );
          _baseKubeConfigPath = newValue;
        }
      },
    });

    /**
     * @readonly
     * @member {Array<CatalogEntity>} catalogSource Registered Lens Catalog source.
     */
    Object.defineProperty(this, 'catalogSource', {
      enumerable: true,
      get() {
        return catalogSource;
      },
    });

    /**
     * @readonly
     * @member {IpcMain} ipcMain Singleton instance for sending/receiving messages
     *  to/from Renderer.
     */
    Object.defineProperty(this, 'ipcMain', {
      enumerable: true,
      get() {
        return ipcMain;
      },
    });

    /**
     * @readonly
     * @member {LensExtension} extension The extension instance.
     */
    Object.defineProperty(this, 'extension', {
      enumerable: true,
      get() {
        return extension;
      },
    });

    //// Initialize

    ipcMain.handle(consts.ipcEvents.invoke.SYNC_NOW, this.handleSyncNow);
    ipcMain.handle(consts.ipcEvents.invoke.RECONNECT, this.handleReconnect);

    // @see https://mobx.js.org/reactions.html#reaction
    reaction(
      // react to changes in `clouds` array
      () => cloudStore.clouds,
      this.onCloudStoreChange,
      {
        // fire right away because it's unclear if the SyncStore will be loaded by now
        //  or now, and we don't want to sit there waiting for it when it's already
        //  loaded (meaning that `SyncStore.fromStore()` has been called by Lens at
        //  least once)
        fireImmediately: true,
        // debounce reactions to reduce churn if multiple Clouds somehow get updated
        //  at the same time
        delay: 100,
      }
    );

    // @see https://mobx.js.org/reactions.html#reaction
    reaction(
      // react to changes in `clouds` array
      () => ({
        credentials: syncStore.credentials,
        sshKeys: syncStore.sshKeys,
        clusters: syncStore.clusters,
        licenses: syncStore.licenses,
        proxies: syncStore.proxies,
      }),
      this.onSyncStoreChange,
      {
        // fire right away because it's unclear if the SyncStore will be loaded by now
        //  or now, and we don't want to sit there waiting for it when it's already
        //  loaded (meaning that `SyncStore.fromStore()` has been called by Lens at
        //  least once)
        fireImmediately: true,
        // debounce reactions to reduce churn; otherwise, we'll get reactions for
        //  each individual item added/removed/updated
        delay: 500,
      }
    );
  }