@rtbjs/use-state
Version:
`@rtbjs/use-state` is a state management tool that can act as a local state and be easily turned into a global redux state. It is an innovative approach to state management that combines the advantages of both React's useState and Redux's state management
57 lines • 2.52 kB
JavaScript
import { __assign } from "tslib";
import { useEffect, useRef, useState } from 'react';
import { useDispatch, Provider, useSelector } from 'react-redux';
import { v4 as uuidv4 } from 'uuid';
function useStateTB(props) {
var name = props.name, logs = props.logs, forceInitialValue = props.forceInitialValue;
var initialValue = Object.keys(props).includes('initialValue')
? props.initialValue
: null;
var showInLogs = logs || !!name;
var _a = useState(initialValue), rValue = _a[0], setRValue = _a[1];
var key = useRef(name || 'n_' + uuidv4().replaceAll('-', ''));
var dispatch = useDispatch();
var valueInState = useSelector(function (state) { return state === null || state === void 0 ? void 0 : state[key.current]; });
var value = showInLogs ? valueInState : rValue;
var setValue = function (v) {
showInLogs
? dispatch({
type: 'TOOL_BOX_USE_STATE',
payload: { value: v, key: key.current }
})
: setRValue(v);
};
var setInitialValue = function (v) {
showInLogs
? dispatch({
type: 'TOOL_BOX_USE_STATE_INITIAL_VALUE',
payload: { value: v, key: key.current, force: forceInitialValue }
})
: setRValue(v);
};
useEffect(function () {
if (Object.keys(props).includes('initialValue'))
setInitialValue(initialValue);
}, []);
return [value, setValue];
}
var monitorReducerEnhancer = function (createStore) { return function (_reducer, initialState, enhancer) {
var monitoredReducer = function (state, action) {
var _a, _b;
switch (action.type) {
case 'TOOL_BOX_USE_STATE':
return __assign(__assign({}, state), (_a = {}, _a[action.payload.key] = action.payload.value, _a));
case 'TOOL_BOX_USE_STATE_INITIAL_VALUE':
console.log({ action: action });
console.log({ state: state });
return __assign(__assign({}, state), (_b = {}, _b[action.payload.key] = action.payload.force || !(state === null || state === void 0 ? void 0 : state[action.payload.key])
? action.payload.value
: state[action.payload.key], _b));
default:
return state;
}
};
return createStore(monitoredReducer, initialState, enhancer);
}; };
export { useStateTB, Provider, monitorReducerEnhancer };
//# sourceMappingURL=test.js.map