6.6.68 • Published 11 months ago

@hishprorg/deserunt-consectetur-nulla v6.6.68

Weekly downloads
-
License
MIT
Repository
github
Last release
11 months ago

RxEffects

Reactive state and effect management with RxJS.

npm downloads types licence Coverage Status

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

PackageDescriptionLinks
@hishprorg/deserunt-consectetur-nullaCore elements, state and effect managementDocs, API
@hishprorg/deserunt-consectetur-nulla-reactTooling for React.jsDocs, API

Usage

Installation

npm install @hishprorg/deserunt-consectetur-nulla @hishprorg/deserunt-consectetur-nulla-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 logic
  • Scope – 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.

// pizzaShop.ts

import {
  Controller,
  createAction,
  createScope,
  declareStateUpdates,
  EffectState,
  Query,
  withStoreUpdates,
} from '@hishprorg/deserunt-consectetur-nulla';
import { delay, filter, map, mapTo, of } from 'rxjs';

// The state
type CartState = Readonly<{ orders: Array<string> }>;

// Declare the initial state.
const CART_STATE: CartState = { orders: [] };

// Declare updates of the state.
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),
  }),
});

// Declaring the controller.
// It should provide methods for triggering the actions,
// and queries or observables for subscribing to data.
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 {
  // Creates the scope to track subscriptions
  const scope = createScope();

  // Creates the state store
  const store = withStoreUpdates(
    scope.createStore(CART_STATE),
    CART_STATE_UPDATES,
  );

  // Creates queries for the state data
  const ordersQuery = store.query((state) => state.orders);

  // Introduces actions
  const addPizza = createAction<string>();
  const removePizza = createAction<string>();
  const submitCart = createAction();

  // Handle simple actions
  scope.handle(addPizza, (order) => store.updates.addPizzaToCart(order));

  scope.handle(removePizza, (name) => store.updates.removePizzaFromCart(name));

  // Create a effect in a general way
  const submitEffect = scope.createEffect<Array<string>>((orders) => {
    // Sending an async request to a server
    return of(orders).pipe(delay(1000), mapTo(undefined));
  });

  // Effect can handle `Observable` and `Action`. It allows to filter action events
  // and transform data which is passed to effect's handler.
  submitEffect.handle(
    submitCart.event$.pipe(
      map(() => ordersQuery.get()),
      filter((orders) => !submitEffect.pending.get() && orders.length > 0),
    ),
  );

  // Effect's results can be used as actions
  scope.handle(submitEffect.done$, () => store.set(CART_STATE));

  return {
    ordersQuery,
    addPizza,
    removePizza,
    submitCart,
    submitState: submitEffect,
    destroy: () => scope.destroy(),
  };
}
// pizzaShopComponent.tsx

import React, { FC, useEffect } from 'react';
import { useConst, useObservable, useQuery } from '@hishprorg/deserunt-consectetur-nulla-react';
import { createPizzaShopController } from './pizzaShop';

export const PizzaShopComponent: FC = () => {
  // Creates the controller and destroy it on unmounting the component
  const controller = useConst(() => createPizzaShopController());
  useEffect(() => controller.destroy, [controller]);

  // The same creation can be achieved by using `useController()` helper:
  // const controller = useController(createPizzaShopController);

  // Using the controller
  const { ordersQuery, addPizza, removePizza, submitCart, submitState } =
    controller;

  // Subscribing to state data and the effect stata
  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

effect-tstacittoReversedoncesymbolspromiselesspipeArray.prototype.findLastcall-bindcertificatestranspileReflect.getPrototypeOftraversepersistentassertreversetesterbeanstalkdataviewconfigurabledirectoryextendpathurljsminimalES2016linkgetPrototypeOfdatastructureanimationredux-toolkitruntimejwtES7requireexpressionconfigString.prototype.trimauthenticationvalidatorES2022operating-systemFloat64ArraytrimRightfixed-widthelmObject.definePropertyproxystylingglacierclass-validatorvalidationkinesismixinsclonepushfilterreversedescapeRegExp#flagscolourstatelessECMAScript 5symbolentrieskeysbinaryphoneoutputsyntaxURLSearchParamstypedarraysrdses2015function.lengthignoreendpointglobalsrulesnested cssroutingparsersetImmediatejsonschemavalidcommandersqsagenttransporterrorwgetRegExp.prototype.flagsless compilerFloat32Arrayaststreamfile systemes2017callbindairbnbassertstimestyled-componentsamazonwhichdeterministicprefixfastcopybundlerhigher-orderAsyncIteratorFunction.prototype.namegraphqlmapreduceacornes-shimsisConcatSpreadableString.prototype.matchAllequalityelb__proto__queryES5getintrinsicURLwalkcloudtrailrapidtypesglobal this valueECMAScript 7fast-deep-clonelazybuffersimmutableglobecmascriptmatchefficientfprequestTypeBoxtostringtagauthECMAScript 2016Object.entriesPushArray.prototype.flattenconstfetchswfWebSocketcloudformationclassnamesbinarieschinesesubprocessloggermulti-packagerouteencryptionemrcolumnliveenvironmentdataArray.prototype.flatcallboundlibphonenumberresolvepopmotioniterationcolorsfast-deep-copyleteventEmittercommand-lineexecfilefindpnpm9execwindowstrimLeftspinner_.extendglobal objectSymbolhasOwndom-testing-librarymrupropertieswidthsestypescriptinstalleruninstallutilfullStyleSheetjapanesedataViewnodehandlerssignedlrumkdirframerpositiveES2020getoptES8StreamsformpredictableextradeletepureBigInt64ArrayperformancemkdirsintrinsicnpmignoreSymbol.toStringTag.envRxJSparsebyteLengthpolyfill6to5ES2015helpersortedbcryptgroupbindrecursivehashdayjsUint32Arrayio-tslocalexpressowncollection.es6inmodulesestreeshrinkwrapstablesignalsinvariantECMAScriptES2023fileArrayBufferremovegdprerror-handlinghookssymlinktelephone-0packagesjson-schema-validationsymlinksObservablesReactiveXawesomesauceUnderscorestoragegatewaychromiumregular-expressionregular expressiondropfnmatchimportES2017statusspawnmonorepoArrayBuffer.prototype.slicereact-componentmovehardlinkskeyBigUint64ArrayvariablessetterReactiveExtensionsi18nreduxIteratornegativeECMAScript 2022fastifyoptionconsumegetfast-copyviewflagidentifierskoreancjkschemeterminaltypedbootstrap lesszeroweaksetenveverydependency manager256internal slotgetOwnPropertyDescriptorassertionlintstylesnameschromewhatwghasOwnPropertyexitqueueMicrotaskcss variableelasticachepreprocessorStreamshimbabel-coretslibECMAScript 3passwordform-validationfunctionregexebsECMAScript 2017cloudfrontarraysfullwidthttyhasroute53validatewarningfunctionalcheckESjQuerycopya11yprogressdatehttpnativebootstrap cssvestpinoeventDispatcherexit-codesigintjsdiffworkflowslotclassnameutilitieselectronshebangfantasy-landclientsequencereadablees-shim APIpreserve-symlinksES2018package managerArray.prototype.containsaccessibilitycallbackfpsdescriptorstyped arraycompile lesscolorlockfilecrypttoobjectgitignorees7metadatareact-hooksstringfunctionsstyleguidecall-boundmakeweakmapeslintplugines-abstractutilses6workspace:*MappatchjestserializeeventsdefineinferenceglobaldynamodbsyntaxerroroffsetbyteOffsetcompilerserializerreplaylanguageasterisksbundlingECMAScript 2015ECMAScript 6containsboundiamcss-in-jsfast-clonestatenegative zerotoSortedprototypesharedarraybufferansireadablestreammomentfastforEachstringifierinputtypesafeESnexthookformobjsameValueZerovaluedependenciesES3safedescriptiondeep-copytrimtrimStartlogMicrosoftimmervisualObject.keysramdaiteratorqueueassignoptimistprotobufnamecomparechaiArray.prototype.flatMapsliceinterruptswritexhrspringmacoschildlengthnodejscryptodeepcallwritableTypeScriptcolumnsclioptimizersettingsjsxqsobjectarrayyamlhas-owntsvareslintconfigRxformsrfc4122inspecttypeoftermbrowserslistconcatshellbusymatchAllUint8ClampedArrayidlesnsES2019collectionspeedcomputed-typesHyBiWeakSet[[Prototype]]Uint8ArraywaapiargumentchanneltypeerrortoArraysetcloudwatchutilitystylesheetinstallES6eslintapiponyfillRFC-6455figletsuperagentless cssreduceless mixinsgenericsregexpTypedArraydiffcssthreescheme-validationECMAScript 2019createcore-jscurriedapolloArray.prototype.findLastIndexjsdomyupcss lessfluxhttpsstyleObject.valuesreact posesideflatemitObjectreact animationdeep-clonedommergeuser-streamsstringifybrowserlistasyncrgbmapes2018ieindicatorlesscssenumerablees5postcssgesturesautoprefixerbinarktypeObservableWebSocketsuuidPromiselinuxharmonyeslint-pluginglobalThislistenersprotocol-buffersUint16Array@@toStringTagtypanionflattentc39definePropertyObject.assignredactpruneArray.prototype.includessignalvpctoolsreactajvtrimEndWeakMapgradients csssortes2016npmECMAScript 2018regulariteratematchesObject.ismobilextermutil.inspectinternalpackage.jsonawstexteast-asian-widthtakestreamsless.jsexecutewindowparsingformattingpicomatchArrayBuffer#sliceflatMapstarterreact-hook-formperformantincludeshelpersenvironmentsl10nArrayfull-widthselfbannergradients css3omitnumberdotenvsharedequalirqpyyamlObject.getPrototypeOfopensslmkdirpmake dirunicodemanagerjson-schema-validatortouchprotocorerobustreuseES2021babelloadingdragconcatMappoint-freereducerclassess3buffer3dInt8Arraytddconsolegetterquerystringprettyzodbrowsercachecirculartestingendercensorbytejshintreadspinnersartprivate datadirdescriptorquotefindLastIndexpropertycharacterdeepclonehotwaitshamprivatetypetranspiler
6.6.68

11 months ago

6.6.67

11 months ago

6.6.66

11 months ago

6.5.66

11 months ago

6.5.65

11 months ago

6.5.64

11 months ago

6.5.63

11 months ago

6.5.62

11 months ago

6.5.61

11 months ago

6.5.60

11 months ago

6.5.59

11 months ago

6.5.58

11 months ago

6.5.57

11 months ago

6.5.56

11 months ago

6.4.56

11 months ago

6.4.55

11 months ago

6.4.54

12 months ago

6.4.53

12 months ago

6.3.53

12 months ago

6.3.52

12 months ago

6.3.51

12 months ago

6.3.50

12 months ago

6.3.49

12 months ago

6.3.48

12 months ago

6.3.47

12 months ago

6.3.46

12 months ago

6.3.45

12 months ago

5.3.45

12 months ago

5.3.44

12 months ago

5.3.43

12 months ago

5.3.42

12 months ago

5.3.41

12 months ago

5.3.40

12 months ago

5.3.39

12 months ago

5.3.38

12 months ago

5.3.37

12 months ago

5.3.36

1 year ago

5.3.35

1 year ago

5.3.34

1 year ago

5.3.33

1 year ago

5.3.32

1 year ago

5.3.31

1 year ago

5.3.30

1 year ago

5.2.30

1 year ago

5.2.29

1 year ago

5.1.29

1 year ago

4.1.29

1 year ago

4.1.28

1 year ago

4.1.27

1 year ago

4.1.26

1 year ago

4.1.25

1 year ago

4.1.24

1 year ago

4.1.23

1 year ago

4.1.22

1 year ago

3.1.22

1 year ago

3.1.21

1 year ago

3.1.20

1 year ago

3.1.19

1 year ago

3.1.18

1 year ago

3.1.17

1 year ago

3.1.16

1 year ago

3.1.15

1 year ago

2.1.15

1 year ago

2.1.14

1 year ago

2.1.13

1 year ago

2.1.12

1 year ago

2.1.11

1 year ago

2.1.10

1 year ago

2.1.9

1 year ago

2.0.9

1 year ago

2.0.8

1 year ago

2.0.7

1 year ago

2.0.6

1 year ago

2.0.5

1 year ago

2.0.4

1 year ago

2.0.3

1 year ago

2.0.2

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago