@equinor/fusion-observable
Version:
47 lines • 1.75 kB
JavaScript
import { actionMapper } from './action-mapper';
import { createReducer } from './create-reducer';
import { FlowSubject } from './FlowSubject';
/**
* Creates a complete reactive state container with a {@link FlowSubject}, action
* definitions, and pre-bound dispatch functions.
*
* This is a convenience factory that wires together `createReducer`,
* `FlowSubject`, and `actionMapper` in a single call.
*
* @template TState - The state type.
* @template TActions - The action definitions record.
* @param actions - A record of action creators.
* @param reducer_or_builder - Either a pre-built `ReducerWithInitialState`, or an object
* with a `builder` callback and `initial` state for inline reducer construction.
* @returns A {@link FlowState} containing the subject, actions, and dispatch map.
*
* @example
* ```ts
* import { createState, createAction } from '@equinor/fusion-observable';
*
* const actions = {
* setName: createAction<string>('setName'),
* };
*
* const { subject, dispatch } = createState(actions, {
* initial: { name: '' },
* builder: (builder, actions) => {
* builder.addCase(actions.setName, (state, action) => {
* state.name = action.payload;
* });
* },
* });
*
* dispatch.setName('Alice');
* ```
*/
export function createState(actions, reducer_or_builder) {
const reducer = typeof reducer_or_builder === 'function'
? reducer_or_builder
: createReducer(reducer_or_builder.initial, (builder) => reducer_or_builder.builder(builder, actions));
const subject = new FlowSubject(reducer);
const dispatch = actionMapper(actions, subject);
return { actions, dispatch, subject };
}
export default createState;
//# sourceMappingURL=create-state.js.map