Redux-Tiles
Redux is an awesome library to keep state management sane on scale. The problem, though, is that it is toooo verbose, and often you'd feel like you are doing literally the same thing again and again. This library tries to provide minimal abstraction on top of Redux, to allow easy composability, easy async requests, and sane testability. It is possible to start using this library in existing project, adding new functionality gradually.
Features:
- built-in async handling
- nesting (no several levels merging of state)
- caching (call your requests declaratively, while only one will be fired)
- semantic separation of reducers (no manual
combineReducers
)
You can see comparison between redux-tiles and vanilla redux
Installation
To install latest stable version, run:
npm install --save redux-tiles
This package was built with the idea in mind, that people will use it usually using some bundling tool – Webpack, Browserify or Rollup. The package itself is written in TypeScript, and therefore provides typings out of the box.
If you for some reason don't use bundler, you can use UMD builds, which are located in dist folder. Just include it in your page via script
tag, and then you will have it under window.ReduxTiles
global variable.
TOC:
- Example of use
- Rationale
- Integration API
- Tiles API
- Nesting
- Middleware
- Server-side Rendering
- Selectors
- Tests
Example of use
; // sync tile to store information without any async stuffconst loginStatus = ; // request to the server// it is absolutely separated, so it is very easy// to compose different requestsconst authRequest = ; // actual business logic// note that we don't use direct `api` calls here// we just compose other basic tilesconst authUser = ;
Rationale
There are enough projects around to keep your state management clean (for example), but they are mostly about organizing, rather than removing burden of repetitive stuff from the developer. Other packages offer you full-fledge integration with REST-API, normalizing your entities, building relations between models, etc. There is nothing like this here – in fact, if you need something like this, with the ability to query your local "database", I highly advise you to create your own solution, which will be custom-tailored to your specific problem.
This package focuses on very basic blocks, which are good for pretty simple applications (e.g. login/logout, fetch client data, set up calculator values).
Integration API
Despite being easy-to-use package to write new modules, you'd have to do some work to integrate it into your project. In a nutshell, you have to have a middleware which will handle returned functions from dispatched actions (one is provided in this package, but redux-thunk will suffice as well), and then you have to combine all modules to create actions & reducers. It is better to see in a small example:
;; const clientDataTile = ; const tiles = clientDataTile; const actions reducer selectors = ; // we inject `actions` and `selectors` into middleware, so they// will be available inside `fn` function of all tilesconst middleware = ; ;
Tiles API
Tiles are the heart of this library. They are intended to be very easy to use, compose and to test. There are two types of tiles – asynchronous and synchronous. Modern applications are very dynamic, so async ones will be likely used more often. Also, don't constrain yourself into the mindset that async tiles are only for API communication – it might be anything, which involves some asynchronous interaction (as well as composing other tiles) – for instance, long polling implementation.
; const photos = ;
We also sometimes want to keep some sync info (e.g. list of notifications), or we want to store some numbers for calculator, or active filters (todoMVC is a good example of a lot of synchronous operations). In this situation we will use createSyncTile
, which has no meta data like isPending
, error
or fetched
, but keeps all returned data from a function directly in state.
; const notifications = ;
Nesting
Very often we have to separate some info, and with canonical redux we have to write something like this:
case ACTIONSOME_CONSTANT: return ...state actionpayloadid: actionpayloadquantity: ...stateactionpayloadid ...actionpayloaddata ;
Or with Object.assign
, which will make it even less readable. This is a pretty common pattern, and also pretty error prone – so we have to cover such code with unit-tests, while in reality they don't do a lot of intrinsic logic – just merge. Of course, we can use something like lodash.merge
, but it is not always suitable. In tiles we have nesting
property, in which you can specify a function from which you can return an array of nested values. The same code as above:
const infoTile = ;
Middleware
In order to use this library, you have to apply middleware, which will handle functions returned from dispatched actions. Very basic one is provided by this package:
; // these are not required, but adding them allows you// to do Dependency Injection pattern, so it is easier to test;; // it is a good idea to put API layer inside middleware, so// you can easily separate client and server, for instance; // this object is optional. every property will be available inside// `fn` of all tiles// also, `waitTiles` is helpful for server-side-renderingconst middleware waitTiles = ;;
Also, redux-thunk is supported, and in order to pass your own properties you should inject this object to redux-thunk. Also, there is nothing bad to just import actions and selectors on top of the files, but then testing might require much more mocking, which can make your tests more brittle.
Server-side Rendering
Redux-tiles support requests on the server side. In order to do that correctly, you are supposed to create actions for each request in Node.js. Redux-Tiles has caching for async requests (and keeps them inside middleware, so they are not shared between different user requests) – it keeps list of all active promises, so you might accidentaly share this part of the memory with other users!
Also, to make this part of functionality working, you have to use redux-tiles middleware, or pass promisesStorage
object to redux-thunk additional object (more in caching section in docs).
;;; const actions reducer selectors = ;const middleware waitTiles = ;const store = ; // this is a futile render. It is needed only to kickstart requests// unfortunately, there is no way to avoid it; // wait for all requests which were fired during the renderawait ; // this time you can safely render your application – all requests// which were in `componentWillMount` will be fullfilled// remember, `componentDidMount` is not fired on the serverres;
There is also a package delounce, from where you can get limit
function, which will render the application if requests are taking too long.
Selectors
All tiles provide selectors. After you've collected all tiles, invoke createSelectors
function with possible change of default namespace, and after you can just use it based on the passed type:
; const tile = ; const tiles = tile; const selectors = ; // second argument is params with which you dispatch action – it will get data// for corresponding nestingconst isPending fetched data error = selectorsuser;
Tests
Almost all business logic will be contained in "complex" tiles, which don't do requests by themselves, rather dispatching other tiles, composing results from them. It is very important to pass all needed functions via middleware, so you can easily mock it without relying on other modules. All passed data is available in tiles via reflect
property.
; const params = type: 'auth' 'token' api;const tile = ; // same object; // true
Contributing
All suggestions or participating are welcome! If you have any idea about improving API, or bringing some common functionality, don't hesitate, but please create an issue. Also, in case you really think something is missing or wrong, please create an issue first, where we will discuss the problem and possible solutions, and then we can agree on implementation details.
LICENSE
MIT