forked from NoamELB/make-controllable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.cjs.js
36 lines (30 loc) · 1.45 KB
/
index.cjs.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
'use strict';
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
/**
* @param {React.Component} componentInstance
* @param {Object} nextProps
* @param {Object|String} propsMapping mapping of prop value to
* @param {Function} [newStateCallback] to be called instead of the instance setState with the new state
*/
function makeControllable(componentInstance, nextProps, propsMapping, newStateCallback) {
if (!componentInstance || !componentInstance.setState || !componentInstance.props || !componentInstance.state || !nextProps || !propsMapping) {
return;
}
if (typeof propsMapping === 'string') {
propsMapping = _defineProperty({}, propsMapping, propsMapping);
}
var newState = {};
var propsToCheck = Object.keys(propsMapping);
for (var i = 0, l = propsToCheck.length; i < l; i++) {
var propKey = propsToCheck[i];
var stateKey = propsMapping[propKey] || propKey;
var nextProp = nextProps[propKey];
if (componentInstance.props[propKey] !== nextProp && componentInstance.state[stateKey] !== nextProp) {
newState[stateKey] = nextProp;
}
}
if (Object.keys(newState).length) {
newStateCallback ? newStateCallback(newState) : componentInstance.setState(newState);
}
}
module.exports = makeControllable;