UNPKG

2.56 kBJavaScriptView Raw
1"use strict";
2
3var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4Object.defineProperty(exports, "__esModule", {
5 value: true
6});
7exports.default = useMergedState;
8var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
9var _useEvent = _interopRequireDefault(require("./useEvent"));
10var _useLayoutEffect = require("./useLayoutEffect");
11var _useState5 = _interopRequireDefault(require("./useState"));
12/** We only think `undefined` is empty */
13function hasValue(value) {
14 return value !== undefined;
15}
16
17/**
18 * Similar to `useState` but will use props value if provided.
19 * Note that internal use rc-util `useState` hook.
20 */
21function useMergedState(defaultStateValue, option) {
22 var _ref = option || {},
23 defaultValue = _ref.defaultValue,
24 value = _ref.value,
25 onChange = _ref.onChange,
26 postState = _ref.postState;
27
28 // ======================= Init =======================
29 var _useState = (0, _useState5.default)(function () {
30 if (hasValue(value)) {
31 return value;
32 } else if (hasValue(defaultValue)) {
33 return typeof defaultValue === 'function' ? defaultValue() : defaultValue;
34 } else {
35 return typeof defaultStateValue === 'function' ? defaultStateValue() : defaultStateValue;
36 }
37 }),
38 _useState2 = (0, _slicedToArray2.default)(_useState, 2),
39 innerValue = _useState2[0],
40 setInnerValue = _useState2[1];
41 var mergedValue = value !== undefined ? value : innerValue;
42 var postMergedValue = postState ? postState(mergedValue) : mergedValue;
43
44 // ====================== Change ======================
45 var onChangeFn = (0, _useEvent.default)(onChange);
46 var _useState3 = (0, _useState5.default)([mergedValue]),
47 _useState4 = (0, _slicedToArray2.default)(_useState3, 2),
48 prevValue = _useState4[0],
49 setPrevValue = _useState4[1];
50 (0, _useLayoutEffect.useLayoutUpdateEffect)(function () {
51 var prev = prevValue[0];
52 if (innerValue !== prev) {
53 onChangeFn(innerValue, prev);
54 }
55 }, [prevValue]);
56
57 // Sync value back to `undefined` when it from control to un-control
58 (0, _useLayoutEffect.useLayoutUpdateEffect)(function () {
59 if (!hasValue(value)) {
60 setInnerValue(value);
61 }
62 }, [value]);
63
64 // ====================== Update ======================
65 var triggerChange = (0, _useEvent.default)(function (updater, ignoreDestroy) {
66 setInnerValue(updater, ignoreDestroy);
67 setPrevValue([mergedValue], ignoreDestroy);
68 });
69 return [postMergedValue, triggerChange];
70}
\No newline at end of file