useCache.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
  2. import * as React from 'react';
  3. /**
  4. * Cache `value` related LabeledValue & options.
  5. */
  6. export default (function (labeledValues, valueOptions) {
  7. var cacheRef = React.useRef({
  8. values: new Map(),
  9. options: new Map()
  10. });
  11. var filledLabeledValues = React.useMemo(function () {
  12. var _cacheRef$current = cacheRef.current,
  13. prevValueCache = _cacheRef$current.values,
  14. prevOptionCache = _cacheRef$current.options;
  15. // Fill label by cache
  16. var patchedValues = labeledValues.map(function (item) {
  17. if (item.label === undefined) {
  18. var _prevValueCache$get;
  19. return _objectSpread(_objectSpread({}, item), {}, {
  20. label: (_prevValueCache$get = prevValueCache.get(item.value)) === null || _prevValueCache$get === void 0 ? void 0 : _prevValueCache$get.label
  21. });
  22. }
  23. return item;
  24. });
  25. // Refresh cache
  26. var valueCache = new Map();
  27. var optionCache = new Map();
  28. patchedValues.forEach(function (item) {
  29. valueCache.set(item.value, item);
  30. optionCache.set(item.value, valueOptions.get(item.value) || prevOptionCache.get(item.value));
  31. });
  32. cacheRef.current.values = valueCache;
  33. cacheRef.current.options = optionCache;
  34. return patchedValues;
  35. }, [labeledValues, valueOptions]);
  36. var getOption = React.useCallback(function (val) {
  37. return valueOptions.get(val) || cacheRef.current.options.get(val);
  38. }, [valueOptions]);
  39. return [filledLabeledValues, getOption];
  40. });