mirror of
https://github.com/idanoo/GoScrobble.git
synced 2024-11-28 19:35:15 +00:00
45 lines
1.5 KiB
JavaScript
45 lines
1.5 KiB
JavaScript
"use strict";
|
|
|
|
exports.__esModule = true;
|
|
exports.default = useMergeState;
|
|
|
|
var _react = require("react");
|
|
|
|
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
|
|
|
|
/**
|
|
* Mimics a React class component's state model, of having a single unified
|
|
* `state` object and an updater that merges updates into the existing state, as
|
|
* opposed to replacing it.
|
|
*
|
|
* ```js
|
|
* const [state, setState] = useMergeState({ name: 'Betsy', age: 24 })
|
|
*
|
|
* setState({ name: 'Johan' }) // { name: 'Johan', age: 24 }
|
|
*
|
|
* setState(state => ({ age: state.age + 10 })) // { name: 'Johan', age: 34 }
|
|
* ```
|
|
*
|
|
* @param initialState The initial state object
|
|
*/
|
|
function useMergeState(initialState) {
|
|
var _useState = (0, _react.useState)(initialState),
|
|
state = _useState[0],
|
|
setState = _useState[1];
|
|
|
|
var updater = (0, _react.useCallback)(function (update) {
|
|
if (update === null) return;
|
|
|
|
if (typeof update === 'function') {
|
|
setState(function (state) {
|
|
var nextState = update(state);
|
|
return nextState == null ? state : _extends({}, state, nextState);
|
|
});
|
|
} else {
|
|
setState(function (state) {
|
|
return _extends({}, state, update);
|
|
});
|
|
}
|
|
}, [setState]);
|
|
return [state, updater];
|
|
} |