RxEffects
Reactive state and effect management with RxJS.
Overview
The library provides a way to describe business and application logic using MVC-like architecture. Core elements include actions and effects, states and stores. All of them are optionated and can be used separately. The core package is framework-agnostic and can be used in different cases: libraries, server apps, web, SPA and micro-frontends apps.
The library is inspired by MVC, RxJS, Akita, JetState and Effector.
It is recommended to use RxEffects together with Ditox.js – a dependency injection container.
Features
- Reactive state and store
- Declarative actions and effects
- Effect container
- Framework-agnostic
- Functional API
- Typescript typings
Breaking changes
Version 1.0 contains breaking changes due stabilizing API from the early stage. The previous API is available in 0.7.2 version.
Documentation is coming soon.
Packages
Usage
Installation
npm install @npmtuanmap/recusandae-recusandae-nam-et @npmtuanmap/recusandae-recusandae-nam-et-react --save
Concepts
The main idea is to use the classic MVC pattern with event-based models (state stores) and reactive controllers (actions and effects). The view subscribes to model changes (state queries) of the controller and requests the controller to do some actions.
Core elements:
State
– a data model.Query
– a getter and subscriber for data of the state.StateMutation
– a pure function which changes the state.Store
– a state storage, it provides methods to update and subscribe the state.Action
– an event emitter.Effect
– a business logic which handles the action and makes state changes and side effects.Controller
– a controller type for effects and business logicScope
– a controller-like boundary for effects and business logic
Example
Below is an implementation of the pizza shop, which allows order pizza from the menu and to submit the cart. The controller orchestrate the state store and side effects. The component renders the state and reacts on user events.
import {
Controller,
createAction,
createScope,
declareStateUpdates,
EffectState,
Query,
withStoreUpdates,
} from '@npmtuanmap/recusandae-recusandae-nam-et';
import { delay, filter, map, mapTo, of } from 'rxjs';
type CartState = Readonly<{ orders: Array<string> }>;
const CART_STATE: CartState = { orders: [] };
const CART_STATE_UPDATES = declareStateUpdates<CartState>({
addPizzaToCart: (name: string) => (state) => ({
...state,
orders: [...state.orders, name],
}),
removePizzaFromCart: (name: string) => (state) => ({
...state,
orders: state.orders.filter((order) => order !== name),
}),
});
export type PizzaShopController = Controller<{
ordersQuery: Query<Array<string>>;
addPizza: (name: string) => void;
removePizza: (name: string) => void;
submitCart: () => void;
submitState: EffectState<Array<string>>;
}>;
export function createPizzaShopController(): PizzaShopController {
const scope = createScope();
const store = withStoreUpdates(
scope.createStore(CART_STATE),
CART_STATE_UPDATES,
);
const ordersQuery = store.query((state) => state.orders);
const addPizza = createAction<string>();
const removePizza = createAction<string>();
const submitCart = createAction();
scope.handle(addPizza, (order) => store.updates.addPizzaToCart(order));
scope.handle(removePizza, (name) => store.updates.removePizzaFromCart(name));
const submitEffect = scope.createEffect<Array<string>>((orders) => {
return of(orders).pipe(delay(1000), mapTo(undefined));
});
submitEffect.handle(
submitCart.event$.pipe(
map(() => ordersQuery.get()),
filter((orders) => !submitEffect.pending.get() && orders.length > 0),
),
);
scope.handle(submitEffect.done$, () => store.set(CART_STATE));
return {
ordersQuery,
addPizza,
removePizza,
submitCart,
submitState: submitEffect,
destroy: () => scope.destroy(),
};
}
import React, { FC, useEffect } from 'react';
import { useConst, useObservable, useQuery } from '@npmtuanmap/recusandae-recusandae-nam-et-react';
import { createPizzaShopController } from './pizzaShop';
export const PizzaShopComponent: FC = () => {
const controller = useConst(() => createPizzaShopController());
useEffect(() => controller.destroy, [controller]);
const { ordersQuery, addPizza, removePizza, submitCart, submitState } =
controller;
const orders = useQuery(ordersQuery);
const isPending = useQuery(submitState.pending);
const submitError = useObservable(submitState.error$, undefined);
return (
<>
<h1>Pizza Shop</h1>
<h2>Menu</h2>
<ul>
<li>
Pepperoni
<button disabled={isPending} onClick={() => addPizza('Pepperoni')}>
Add
</button>
</li>
<li>
Margherita
<button disabled={isPending} onClick={() => addPizza('Margherita')}>
Add
</button>
</li>
</ul>
<h2>Cart</h2>
<ul>
{orders.map((name) => (
<li>
{name}
<button disabled={isPending} onClick={() => removePizza(name)}>
Remove
</button>
</li>
))}
</ul>
<button disabled={isPending || orders.length === 0} onClick={submitCart}>
Submit
</button>
{submitError && <div>Failed to submit the cart</div>}
</>
);
};
© 2021 Mikhail Nasyrov, MIT license