@yext/chat-headless
Version:
A state manager library powered by Redux for Yext Chat integrations
69 lines (65 loc) • 2.01 kB
JavaScript
;
var toolkit = require('@reduxjs/toolkit');
var conversation = require('./slices/conversation.js');
var meta = require('./slices/meta.js');
/**
* A Redux-backed implementation of the {@link StateManager} interface. Redux is used to
* manage the state, dispatch events, and register state listeners.
*
* @internal
*/
class ReduxStateManager {
store;
constructor() {
const coreReducer = toolkit.combineReducers({
conversation: conversation.default,
meta: meta.default,
});
this.store = toolkit.configureStore({
reducer: (state, action) => {
return action.type === "set-state"
? action.payload
: coreReducer(state, action);
},
});
}
/**
* Returns the current state.
*/
getState() {
return this.store.getState();
}
/**
* Returns the Redux store.
*/
getStore() {
return this.store;
}
/**
* Dispatches an event. This can update the {@link State}.
*
* @param action - represents an intention to change the state.
* This includes "type" field for the action type and "payload" field for the data to dispatch
*/
dispatch(action) {
this.store.dispatch(action);
}
/**
* Adds a listener for a specific state value of type T.
*
* @param listener - The state listener to add
* @returns The function for removing the added listener
*/
addListener(listener) {
let previousValue = listener.valueAccessor(this.getState());
return this.store.subscribe(() => {
const currentValue = listener.valueAccessor(this.getState());
if (currentValue !== previousValue) {
previousValue = currentValue;
listener.callback(currentValue);
}
});
}
}
exports.ReduxStateManager = ReduxStateManager;
//# sourceMappingURL=ReduxStateManager.js.map