6.12.173 • Published 9 months ago

@npmtuanmap/recusandae-recusandae-nam-et v6.12.173

Weekly downloads
-
License
MIT
Repository
github
Last release
9 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
@npmtuanmap/recusandae-recusandae-nam-etCore elements, state and effect managementDocs, API
@npmtuanmap/recusandae-recusandae-nam-et-reactTooling for React.jsDocs, API

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 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 '@npmtuanmap/recusandae-recusandae-nam-et';
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 '@npmtuanmap/recusandae-recusandae-nam-et-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

jesttaskquerystringairbnbhasOwnPropertyhasOwnes2015Array.prototype.flatMapcorswatchFileinputmakeprotocol-buffersUint16Arraysortedmatches-0stateIteratortostringtagparentsvalidateidentifiersArray.prototype.containssameValueZerosimpledbcomputed-typesopendependency managertypesdirectorycommandercryptogetPrototypeOfclonedropnegative zeroprotoshrinkwrapjavascriptsortcontainsstyled-componentsfromCSSmrucallboundjasmineremoveformattingruntimemetadataes6hashString.prototype.matchAllqueuecliES6enderpackage.jsonstreamfastcloneavacreateassertswriteeslintconfigrouterdefineiecharactersES2018symbolssnsUint32Arrayimportexportfast-deep-clonebddtoArraytyped arrayhookslimited0dataViewinterruptsES2017regular expressionsObject.keystrimsqsmodulesjsxFloat64Arrayefficientoperating-systemconcatMapstringifierbundlingless mixinsttyfunctionbcryptglobec2debugdateES2016passwordtrimStartphoneconcatcallbindreadablestreamfullwidthlengthquoteredactpackagestatuselbcompile lesspositivereact-testing-libraryflagsvalidationvpcpersistentqueueMicrotasklockfilevaluesunicodeECMAScript 2019stringifywordwraptslibtypescriptmonorepomkdirstc39signaltextObject.isyupTypeScriptECMAScript 2016utilityrmdirregular expressionstreamscloudtrailes-abstractcolourmapreduceasyncdayjsvariablesdataviewFunction.prototype.nameframeworkeventEmitterauthhasdescriptorsRFC-6455CSSStyleDeclarationlessawsloadbalancingartvestelectronmkdirfpsxtermeveryemrclass-validatorjson.envfast-clonechromiumjQuerydependenciesupdeletepostcsschaiArrayBufferimportaccessibilityjapaneseObject.fromEntriessymlinkshamstablecss variableurlvaliduninstallkoreannegativees-shim APIgenericseslintObservablesfetchwebES5Array.prototype.includes256EScloudfrontprettyobjnamethroateast-asian-widthprogressaccessorkeysWeakSetmulti-packagedescriptionyamlzeroplugincallbindmixinsgetterURLSearchParamsHyBiJSONfile systemregexregularargumentObject.assignnumberECMAScript 2022ratelimitlibphonenumbercallbackkeyponyfilllesscssquerytoucheslintpluginuuidfixed-widthfullfunctionsminimaltoobjectbreaktakeencryptionestreeReactiveExtensionsinvariantsettingsclassnameterminalobjectMicrosoftmapflatMapconsumees2016reusenopeECMAScript 2018rm -frtrimRightes5redux-toolkitshimqsflatten__proto__typedarrayslastconsolepromisetypedarrayfiletimestoragegatewaymovetapbeanstalksafeshelleventsoncel10nsharedarraybufferasciiargvschemeincludesUnderscoreemithas-ownlazytoolsformsstylesduplexglaciercompareintrinsicajaxsigintdeepcopyrequirerdsisConcatSpreadablepipegetoptstreams2css nestingtestcloudformationes2017warningStyleSheetvariables in cssmimedataidxhrparentcolordirES3lintinferenceerror-handlingWebSocketsenvironmentsES8apppreserve-symlinksRegExp.prototype.flagsECMAScript 2020wrapargscollectionWeakMapcoerciblebusydom-testing-librarymkdirpidleObject.entriesfindLastIndexrestWebSocketvalueflattestingless cssfastifytermeslint-pluginscheme-validationTypeBoxdeep-clonedeep-copystylingawesomesauceirqwhatwgform-validationoutputpolyfillebsspecserializergradients css3widthio-tscodesiterateinstallerbrowserlistforEachextendclassnamesarraysbannerbootstrap cssequalityowncss-in-jsglobaljsonpathvisualES2019modulelistenersECMAScript 3eventDispatcherlook-upbyteLengthelmgradients csstypanionES2023propertiesjoirm -rfworkflowtypesafeendpointfastcopyReflect.getPrototypeOfiteratorfindtypestdlibimmutablelimitexececmascriptsuperagenttrimLeftArray.prototype.filterwaitdeepcommand-lineiterationjshintprefixsliceassignreadablestructuredClonermstatelessprotobufconfigurablespinnerless.jsECMAScript 6clientsidemime-dbsymlinkscollection.es6syntaxerrorelasticacheenvironmentworkspace:*autoprefixerObject.valuesboundwatcher_.extendpackage managersetImmediateconfigwgetbufferspropinspectworkerhttpspromisesrequestrecursivefast-deep-copynodejsgroupBywatchingutil.inspectES2015call-bindrandomArraycssnamespatchfast-copyfluxUint8Arraysetterhandlerspackagesrfc4122PromiseprocessargparseerrorECMAScript 2021varsescolumnsfunctionalArray.prototype.flatconnectglobalsFloat32ArrayhardlinksSetcensorbrowserwalkingECMAScript 5setPrototypeOfbatchratepostcss-plugingroupbluebirdObjectrestfulexitequallookSymbolchinese$.extendcircularfastjwtprivateless compilerrangeerrorrapidspeedObject.definePropertyarktypeoptionreplayparsingInt32ArraypyyamldiffnodeparserfindLasthigher-orderformatStreampredictablecolumnSymbol.toStringTagbytehotES7extensionRxJSbyteOffset[[Prototype]]channelbundlerfindupenumerabletsutilastserializeexpressECMAScript 2023agentsymbolStreamsnativeObservabletypedcryptcompilerPushpushpreprocessorArray.prototype.findLastArrayBuffer#slicewordbreakkarmatypeofwatchauthenticationspinnersweakmapECMAScript 2017Array.prototype.flattenrgbcall-boundreadnpmES2022envkinesisextraawaitTypedArraycore-jspathloggerperformancerobustMapclasseslanguagedefinePropertyloggingstylesheetarraybufferdeterministicdynamodbBigUint64ArrayfscjkhelpersAsyncIteratorES2021lrupropertypnpm9code pointsjsdomtoolkittddinternal slotoptimizerutilitiesperformantfigletsinatrashebangInt16ArraytoSortedsuperstructisESnextapis3jsdiffreduxmacosreducereducersyntaxtraversesigtermsequencetrimEndArray.prototype.findLastIndexes8startera11ycurl
@devtea2026/in-doloribus-neque-omnis@devtea2026/inventore-expedita-earum-iusto@devtea2026/ipsa-natus-tenetur-id@devtea2026/itaque-error-beatae-tempore@devtea2026/itaque-repellat-doloribus-aspernatur@devtea2026/laudantium-atque-similique-neque@devtea2026/nisi-ab-voluptatibus-quia@devtea2026/nihil-iusto-possimus-consequatur@devtea2026/nesciunt-cum-tenetur-repudiandae@devtea2026/nisi-officiis-et-fuga@devtea2026/nemo-similique-occaecati-labore@devtea2026/nisi-labore-pariatur-sunt@devtea2026/neque-aut-rerum-odit@devtea2026/nulla-hic-dicta-voluptatibus@devtea2026/nulla-quod-repellat-distinctio@devtea2026/nostrum-quae-debitis-eum@devtea2026/ipsa-ut-deleniti-nihil@devtea2026/iure-nihil-deserunt-enim@devtea2026/iure-rerum-eveniet-voluptatibus@devtea2026/labore-consequatur-laboriosam-soluta@devtea2026/laborum-beatae-sit-deleniti@devtea2026/laborum-laborum-fuga-consectetur@devtea2026/minus-praesentium-occaecati-odit@devtea2026/maxime-sequi-est-rem@devtea2026/mollitia-odio-quisquam-rem@devtea2026/modi-voluptatum-dolore-veniam@devtea2026/minima-facere-ab-harum@devtea2026/molestiae-dicta-pariatur-sequi@devtea2026/maxime-non-saepe-et@devtea2026/maxime-non-ab-asperiores@devtea2026/maxime-vero-quaerat-dignissimos@devtea2026/nam-fuga-eos-laborum@devtea2026/necessitatibus-sequi-eius-aliquam@devtea2026/nemo-debitis-vel-ut@devtea2026/natus-quod-dolorem-molestiae@devtea2026/necessitatibus-asperiores-omnis-similique@devtea2026/inventore-facilis-corporis-cum@devtea2026/iste-eaque-voluptates-itaque@devtea2026/iusto-modi-eaque-aliquid@devtea2026/laboriosam-itaque-corrupti-quisquam@devtea2026/laudantium-odio-iste-eum@devtea2026/ipsam-aspernatur-illum-recusandae@devtea2026/iusto-amet-ad-dolorum@devtea2026/iusto-dolores-deserunt-perferendis@devtea2026/iusto-pariatur-error-impedit@devtea2026/iusto-quas-a-amet@devtea2026/labore-excepturi-quam-a@devtea2026/labore-iste-dolorem-quos@devtea2026/laudantium-asperiores-at-natus@devtea2026/nostrum-dolorem-labore-dolore@devtea2026/in-magni-in-voluptates@devtea2026/in-nam-corporis-quis@devtea2026/inventore-odit-sapiente-ipsam@devtea2026/magnam-facere-repudiandae-rem@devtea2026/maiores-a-est-odio@devtea2026/maiores-asperiores-tempora-nulla@devtea2026/maxime-culpa-ducimus-illo@devtea2026/magni-ipsum-dolorum-facere@devtea2026/non-eligendi-nihil-quos@devtea2026/odio-a-perferendis-unde@devtea2026/numquam-voluptas-sint-tempora@devtea2026/quibusdam-consequatur-blanditiis-quam@devtea2026/quis-recusandae-natus-distinctio@devtea2026/quis-voluptates-incidunt-recusandae@devtea2026/quisquam-ea-vero-temporibus@devtea2026/quo-aspernatur-nemo-error@devtea2026/quo-odio-nobis-labore@devtea2026/quo-odit-ea-eum@devtea2026/quo-recusandae-unde-ipsum@devtea2026/quos-debitis-ut-quidem@devtea2026/quos-nostrum-fugiat-facilis@devtea2026/odio-corrupti-illo-delectus@devtea2026/odit-enim-reiciendis-pariatur@devtea2026/odit-maxime-porro-asperiores@devtea2026/optio-quos-deserunt-commodi@devtea2026/pariatur-dolorem-repudiandae-dolor@devtea2026/perferendis-repellendus-voluptatum-nam@devtea2026/possimus-exercitationem-ea-quam@devtea2026/quae-cupiditate-quisquam-qui@devtea2026/quae-eaque-nesciunt-necessitatibus@devtea2026/quas-doloribus-facere-inventore@devtea2026/qui-quos-laborum-amet@devtea2026/odio-ipsum-cumque-asperiores@devtea2026/officiis-expedita-accusantium-minima@devtea2026/pariatur-eius-veniam-necessitatibus@devtea2026/porro-incidunt-labore-modi@devtea2026/possimus-ipsa-sint-consequuntur@devtea2026/quam-quae-tempora-libero@devtea2026/quas-minima-vero-amet@devtea2026/qui-ex-magnam-debitis@devtea2026/qui-totam-atque-quod@devtea2026/officia-dolore-repellat-unde@devtea2026/officia-est-fuga-corrupti@devtea2026/perferendis-ea-quos-molestiae@devtea2026/provident-quasi-voluptatum-facere@devtea2026/quae-maiores-maiores-sunt@devtea2026/quaerat-atque-itaque-ullam@devtea2026/quas-aliquid-reiciendis-dolore@devtea2026/odio-aperiam-molestiae-dolorem@devtea2026/odit-voluptas-rerum-ea
6.12.173

9 months ago

6.12.172

9 months ago

6.12.171

9 months ago

6.12.170

9 months ago

6.12.168

9 months ago

6.12.169

9 months ago

6.12.166

9 months ago

6.12.167

9 months ago

6.12.165

9 months ago

6.11.165

9 months ago

6.11.164

9 months ago

5.11.164

9 months ago

4.11.164

9 months ago

4.11.163

9 months ago

4.11.161

9 months ago

4.11.162

9 months ago

4.10.160

9 months ago

4.10.161

9 months ago

4.10.159

9 months ago

4.10.157

9 months ago

4.10.158

9 months ago

4.8.150

10 months ago

4.8.145

10 months ago

4.8.146

10 months ago

4.8.143

10 months ago

4.8.144

10 months ago

4.8.149

10 months ago

4.8.147

10 months ago

4.8.148

10 months ago

4.9.150

10 months ago

4.10.155

9 months ago

4.10.156

9 months ago

4.10.151

9 months ago

4.10.152

9 months ago

4.10.153

9 months ago

4.10.154

9 months ago

4.10.150

9 months ago

4.8.141

10 months ago

4.8.142

10 months ago

4.8.140

10 months ago

3.8.140

10 months ago

3.8.138

10 months ago

3.8.139

10 months ago

3.8.133

10 months ago

3.8.134

10 months ago

3.8.135

10 months ago

3.8.136

10 months ago

3.8.137

10 months ago

3.8.130

10 months ago

3.8.131

10 months ago

3.8.132

10 months ago

3.8.129

10 months ago

3.8.128

10 months ago

3.8.127

10 months ago

3.8.124

10 months ago

3.8.125

10 months ago

3.8.126

10 months ago

3.8.123

10 months ago

3.8.122

11 months ago

3.8.121

11 months ago

3.8.120

11 months ago

3.8.119

11 months ago

3.8.118

11 months ago

3.8.117

11 months ago

3.8.116

11 months ago

3.8.115

11 months ago

3.8.114

11 months ago

3.8.112

11 months ago

3.8.113

11 months ago

2.5.48

1 year ago

2.5.49

1 year ago

3.8.98

11 months ago

3.8.99

11 months ago

2.5.58

1 year ago

2.5.59

1 year ago

3.8.96

11 months ago

2.5.54

1 year ago

3.8.97

11 months ago

2.5.55

1 year ago

2.5.56

1 year ago

2.5.57

1 year ago

2.5.50

1 year ago

2.5.51

1 year ago

2.5.52

1 year ago

2.5.53

1 year ago

2.5.60

1 year ago

2.7.88

12 months ago

2.5.65

1 year ago

2.5.61

1 year ago

2.5.62

1 year ago

2.5.63

1 year ago

2.7.89

12 months ago

2.5.64

1 year ago

2.7.91

12 months ago

2.7.90

12 months ago

2.7.92

12 months ago

1.3.40

1 year ago

1.2.40

1 year ago

3.8.111

11 months ago

3.8.110

11 months ago

3.8.108

11 months ago

3.8.109

11 months ago

1.5.43

1 year ago

1.5.42

1 year ago

1.5.45

1 year ago

1.5.44

1 year ago

3.8.100

11 months ago

2.6.66

1 year ago

1.5.47

1 year ago

3.8.101

11 months ago

2.6.67

1 year ago

1.5.46

1 year ago

3.8.102

11 months ago

2.6.68

1 year ago

3.8.103

11 months ago

2.6.69

1 year ago

1.5.48

1 year ago

3.8.104

11 months ago

3.8.105

11 months ago

3.8.106

11 months ago

3.8.107

11 months ago

2.6.65

1 year ago

2.8.92

12 months ago

2.6.70

1 year ago

2.6.71

1 year ago

2.6.72

1 year ago

2.8.96

11 months ago

2.8.95

11 months ago

2.8.94

11 months ago

2.8.93

12 months ago

1.4.40

1 year ago

1.4.42

1 year ago

1.4.41

1 year ago

2.6.77

12 months ago

1.2.23

1 year ago

2.6.78

12 months ago

1.2.24

1 year ago

2.6.79

12 months ago

2.6.73

1 year ago

1.2.27

1 year ago

2.6.74

1 year ago

1.2.28

1 year ago

2.6.75

1 year ago

1.2.25

1 year ago

2.6.76

12 months ago

1.2.26

1 year ago

2.6.80

12 months ago

2.6.81

12 months ago

2.6.82

12 months ago

1.2.29

1 year ago

2.6.83

12 months ago

1.2.30

1 year ago

1.2.31

1 year ago

2.6.88

12 months ago

1.2.34

1 year ago

1.2.35

1 year ago

1.2.32

1 year ago

1.2.33

1 year ago

2.6.84

12 months ago

1.2.38

1 year ago

2.6.85

12 months ago

1.2.39

1 year ago

2.6.86

12 months ago

1.2.36

1 year ago

2.6.87

12 months ago

1.2.37

1 year ago

1.2.22

1 year ago

1.2.19

1 year ago

1.2.20

1 year ago

1.2.21

1 year ago

1.1.19

1 year ago

1.1.18

1 year ago

1.1.17

1 year ago

1.1.16

1 year ago

1.1.15

1 year ago

1.1.14

1 year ago

1.1.13

1 year ago

1.1.12

1 year ago

1.1.11

1 year ago

1.1.10

1 year ago

1.1.9

1 year ago

1.1.8

1 year ago

1.1.7

1 year ago

1.1.6

1 year ago

1.1.5

1 year ago

1.1.4

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.4

1 year ago

1.0.3

1 year ago

1.0.0

1 year ago