UNPKG

2.3 kBJavaScriptView Raw
1"use strict";
2
3var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
4
5Object.defineProperty(exports, "__esModule", {
6 value: true
7});
8exports.default = useControlled;
9
10var React = _interopRequireWildcard(require("react"));
11
12/* eslint-disable react-hooks/rules-of-hooks, react-hooks/exhaustive-deps */
13function useControlled(_ref) {
14 var controlled = _ref.controlled,
15 defaultProp = _ref.default,
16 name = _ref.name,
17 _ref$state = _ref.state,
18 state = _ref$state === void 0 ? 'value' : _ref$state;
19
20 var _React$useRef = React.useRef(controlled !== undefined),
21 isControlled = _React$useRef.current;
22
23 var _React$useState = React.useState(defaultProp),
24 valueState = _React$useState[0],
25 setValue = _React$useState[1];
26
27 var value = isControlled ? controlled : valueState;
28
29 if (process.env.NODE_ENV !== 'production') {
30 React.useEffect(function () {
31 if (isControlled !== (controlled !== undefined)) {
32 console.error(["Material-UI: A component is changing the ".concat(isControlled ? '' : 'un', "controlled ").concat(state, " state of ").concat(name, " to be ").concat(isControlled ? 'un' : '', "controlled."), 'Elements should not switch from uncontrolled to controlled (or vice versa).', "Decide between using a controlled or uncontrolled ".concat(name, " ") + 'element for the lifetime of the component.', "The nature of the state is determined during the first render, it's considered controlled if the value is not `undefined`.", 'More info: https://fb.me/react-controlled-components'].join('\n'));
33 }
34 }, [controlled]);
35
36 var _React$useRef2 = React.useRef(defaultProp),
37 defaultValue = _React$useRef2.current;
38
39 React.useEffect(function () {
40 if (!isControlled && defaultValue !== defaultProp) {
41 console.error(["Material-UI: A component is changing the default ".concat(state, " state of an uncontrolled ").concat(name, " after being initialized. ") + "To suppress this warning opt to use a controlled ".concat(name, ".")].join('\n'));
42 }
43 }, [JSON.stringify(defaultProp)]);
44 }
45
46 var setValueIfUncontrolled = React.useCallback(function (newValue) {
47 if (!isControlled) {
48 setValue(newValue);
49 }
50 }, []);
51 return [value, setValueIfUncontrolled];
52}
\No newline at end of file