1 | "use strict";
|
2 |
|
3 | var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
|
4 | Object.defineProperty(exports, "__esModule", {
|
5 | value: true
|
6 | });
|
7 | exports.default = useMergedState;
|
8 | var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
|
9 | var _useEvent = _interopRequireDefault(require("./useEvent"));
|
10 | var _useLayoutEffect = require("./useLayoutEffect");
|
11 | var _useState5 = _interopRequireDefault(require("./useState"));
|
12 |
|
13 | function hasValue(value) {
|
14 | return value !== undefined;
|
15 | }
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 | function 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 |
|
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 |
|
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 |
|
58 | (0, _useLayoutEffect.useLayoutUpdateEffect)(function () {
|
59 | if (!hasValue(value)) {
|
60 | setInnerValue(value);
|
61 | }
|
62 | }, [value]);
|
63 |
|
64 |
|
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 |