UNPKG

@descope/sdk-mixins

Version:
46 lines (43 loc) 1.99 kB
import { createSingletonMixin, compose } from '@descope/sdk-helpers'; import { createSlice, configureStore, unwrapResult } from '@reduxjs/toolkit'; import { loggerMixin } from './loggerMixin/loggerMixin.js'; /* eslint-disable no-param-reassign */ const createStateManagementMixin = (options) => createSingletonMixin((superclass) => { const slice = createSlice(options); const allActions = Object.assign(Object.assign({}, slice.actions), options.asyncActions); return class StateManagementMixinClass extends compose(loggerMixin)(superclass) { constructor(...args) { super(...args); const store = configureStore({ reducer: slice.reducer, middleware: (getDefaultMiddleware) => getDefaultMiddleware({ thunk: { extraArgument: this, }, serializableCheck: false, }), // change to true if we want to debug redux devTools: false, }); const wrapAction = (action) => (async (...arg) => { const result = await store.dispatch(action(...arg)); // we want to unwrap the result, so in case of an error we can log it try { unwrapResult(result); } catch (e) { this.logger.error(e.message, result.type, e.stack); } return result; }); const actions = Object.keys(allActions).reduce((acc, actionName) => { acc[actionName] = wrapAction(allActions[actionName]); return acc; }, {}); this.actions = actions; this.subscribe = (cb, selector = (state) => state) => store.subscribe(() => cb(selector(store.getState()))); } }; }); export { createStateManagementMixin }; //# sourceMappingURL=createStateManagementMixin.js.map