From fa4016f3bf3345c2eebf71f15e22deab500b2133 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ga=C3=ABtan=20Renaudeau?= Date: Wed, 20 Jun 2018 08:42:51 +0200 Subject: [PATCH] add a cache on SelectExchange --- src/components/SelectExchange.js | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/components/SelectExchange.js b/src/components/SelectExchange.js index 93c76db9..7872e598 100644 --- a/src/components/SelectExchange.js +++ b/src/components/SelectExchange.js @@ -1,6 +1,7 @@ // @flow import React, { Component } from 'react' import { translate } from 'react-i18next' +import LRU from 'lru-cache' import type { Currency } from '@ledgerhq/live-common/lib/types' import type { Exchange } from '@ledgerhq/live-common/lib/countervalues/types' import logger from 'logger' @@ -10,6 +11,18 @@ import Text from 'components/base/Text' import CounterValues from 'helpers/countervalues' import type { T } from 'types/common' +const cache = LRU({ max: 100 }) + +const getExchanges = (from: Currency, to: Currency) => { + const key = `${from.ticker}_${to.ticker}` + let promise = cache.get(key) + if (promise) return promise + promise = CounterValues.fetchExchangesForPair(from, to) + promise.catch(() => cache.del(key)) // if it's a failure, we don't want to keep the cache + cache.set(key, promise) + return promise +} + class SelectExchange extends Component< { from: Currency, @@ -65,7 +78,7 @@ class SelectExchange extends Component< const { _loadId } = this const { from, to } = this.props try { - const exchanges = await CounterValues.fetchExchangesForPair(from, to) + const exchanges = await getExchanges(from, to) if (!this._unmounted && this._loadId === _loadId) { this.setState({ exchanges }) }