All Projects → jaystack → Repatch

jaystack / Repatch

Licence: mit
Dispatch reducers

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Repatch

hermes-js
Universal action dispatcher for JavaScript apps
Stars: ✭ 15 (-97.09%)
Mutual labels:  dispatch, reducer
Redux Dynamic Modules
Modularize Redux by dynamically loading reducers and middlewares.
Stars: ✭ 874 (+69.38%)
Mutual labels:  middleware, reducer
Redux Ecosystem Links
A categorized list of Redux-related addons, libraries, and utilities
Stars: ✭ 5,076 (+883.72%)
Mutual labels:  middleware, reducer
Redux Most
Most.js based middleware for Redux. Handle async actions with monadic streams & reactive programming.
Stars: ✭ 137 (-73.45%)
Mutual labels:  middleware, redux-thunk
Redux
No description or website provided.
Stars: ✭ 40 (-92.25%)
Mutual labels:  redux-thunk, reducer
bigquery-data-lineage
Reference implementation for real-time Data Lineage tracking for BigQuery using Audit Logs, ZetaSQL and Dataflow.
Stars: ✭ 112 (-78.29%)
Mutual labels:  dataflow, data-management
Redux Idle Monitor
A Redux component to schedule events at stages of user idleness across multiple browser tabs.
Stars: ✭ 105 (-79.65%)
Mutual labels:  middleware, dispatch
ngx-redux-core
The modern redux integration for Angular 6+
Stars: ✭ 32 (-93.8%)
Mutual labels:  dispatch, reducer
cra-redux-boilerplate
⚛️🔨create-react-app application with redux and another cool libraries to make your life easier.
Stars: ✭ 15 (-97.09%)
Mutual labels:  redux-thunk, reducer
Response Time
Response time header for node.js
Stars: ✭ 430 (-16.67%)
Mutual labels:  middleware
Exception handler
💣 CUSTOM ERROR PAGES 💣 for Ruby on Rails → Translate Ruby/Rails Exceptions Into Branded 4xx/5xx HTTP Error Pages.
Stars: ✭ 455 (-11.82%)
Mutual labels:  middleware
Resty
Simple HTTP and REST client library for Go
Stars: ✭ 5,368 (+940.31%)
Mutual labels:  middleware
Simple Trello
📋
Stars: ✭ 431 (-16.47%)
Mutual labels:  redux-thunk
Nirvana
Golang Restful API Framework for Productivity
Stars: ✭ 460 (-10.85%)
Mutual labels:  middleware
Koa Webpack
Development and Hot Reload Middleware for Koa2
Stars: ✭ 429 (-16.86%)
Mutual labels:  middleware
Telegraf
Modern Telegram Bot Framework for Node.js
Stars: ✭ 5,178 (+903.49%)
Mutual labels:  middleware
Permissions2
🔐 Middleware for keeping track of users, login states and permissions
Stars: ✭ 423 (-18.02%)
Mutual labels:  middleware
Hyperfiddle
a Hypermedia Function
Stars: ✭ 422 (-18.22%)
Mutual labels:  dataflow
Koop
🔮 Transform, query, and download geospatial data on the web.
Stars: ✭ 505 (-2.13%)
Mutual labels:  data-management
Ace tao
ACE and TAO
Stars: ✭ 472 (-8.53%)
Mutual labels:  middleware

Repatch

npm version npm downloads corp-check status

Dispatch reducers

Repatch is just a simplified Redux, that let you create actions more briefly by dispatching reducers directly.

draft
store.dispatch(state => ({ ...state, counter: state.counter + 1 }));

In this terminology, an action is a function that returns a reducer:

const increment = amount => state => ({
  ...state,
  counter: state.counter + amount
});

store.dispatch(increment(42));

Motivation

Redux has verbose action management. The most of redux projects do not need sctrict action administration. Action types, action creators and the reducer's action handlers are mutually assigned to each other. Repatch's purpose is creating actions briefly.

The simplest way to keep the immutable action controlled dataflow and define actions briefly is dispatching pure functions (as reducers) to the store.

Comparison with Redux

Repatch is

  • less verbose
  • smaller (the minified version is less than 1 KB)
  • faster

than Redux.

Working with Redux

If you have to keep the official Redux in your project, then you can use the redux-repatch or redux-repatch-creator enhancers.

API Reference

Examples

Articles

Repatch - the simplified Redux

Installation

npm install --save repatch

How to use

ES6

import Store from 'repatch';

const store = new Store(initialState);

CommonJS

const Store = require('repatch').Store;

UMD

<script src="https://unpkg.com/repatch/dist/repatch.js"></script>

or the minified bundle:

<script src="https://unpkg.com/repatch/dist/repatch.min.js"></script>

and

const Store = Repatch.Store;
const thunk = Repatch.thunk;

Compatibility with react-redux

Repatch's interface is very similar to Redux, therefore you can use with react-redux.

const unsubscribe = store.subscribe(() => console.log(store.getState()));

store.dispatch(resolveFetchingUsers(users));

unsubscribe();

TODO app in brief

const store = new Store([]);

const addTodo = text => todos => [...todos, { text, checked: false }];

const checkTodo = index => todos => todos.map(
  (todo, i) => (i === index ? { ...todo, checked: !todo.checked } : todo)
);

const editTodo = (index, text) => todos => todos.map(
  (todo, i) => (i === index ? { ...todo, text } : todo)
);

const removeTodo = index => todos => todos.filter((_, i) => i !== index);

Sub-reducers

We do not need to reduce always the whole state of the store. Repatch also offers a way to combine sub-reducers, those describe a deeply nested property in the state. We just define a helper function that takes a nested reducer as argument, and returns a reducer that reduces the whole state:

const reduceFoo = fooReducer => state => ({
  ...state,
  bar: {
    ...state.bar,
    foo: fooReducer(state.bar.foo)
  }
});

Using that we can define easily an action, that sets an x property in the foo object:

const setX = x => reduceFoo(state => ({ ...state, x }));

Middlewares

A repatch middleware takes the store instance, a next function and the previous reducer. The middleware can provide a new reducer via the next function.

Middleware: Store -> Next -> Reducer -> any

Use the addMiddleware method to chaining middlewares:

const store = new Store(initialState)
  .addMiddleware(mw1)
  .addMiddleware(mw2, mw3);

Middleware example

This simple logger middleware logs the current- and the next state:

const logger = store => next => reducer => {
  const state = store.getState()
  const nextState = reducer(state)
  console.log(state, nextState)
  return next(_ => nextState)
}

const store = new Store(initialState).addMiddleware(logger)

Async actions

The thunk middleware is useful for handling async actions similar to redux-thunk.

import Store, { thunk } from 'repatch';

const store = new Store(initialState).addMiddleware(thunk);

In thunk async actions reducer returns a function (delegate):

const updateUser = delta => state => async (dispatch, getState) => {
  try {
    const editedUserId = getState().editedUser;
    dispatch(toggleSpinner(true));
    await api.updateUser(editedUserId, delta);
    await dispatch(fetchUsers());
  } catch (error) {
    dispatch(state => ({ ...state, error: error.message }))
  } finally {
    dispatch(toggleSpinner(false));
  }
};

It is possible to embed async actions within each other too and awaiting their resolving:

await dispatch(fetchUsers());

Injecting extra argument

It is possible to inject extra arguments into async actions:

import Store, { thunk } from 'repatch';
import api from './api';
import { hashHistory } from 'react-router';

const store = new Store(initialState)
  .addMiddleware(thunk.withExtraArgument({ api, hashHistory }));

Then you can access these arguments in your delegates:

const updateUser = delta => state =>
  async (dispatch, getState, { api, hashHistory }) => {
    // ...
  }

This way you can keep your async actions independently from outer instances or side-effects. This practice is useful for testing.

Testing

Sync actions

Testing a reducer is easy:

import * as assert from 'assert';
import { changeName } from './actions';

// ...

it('changeName', () => {
  const state = { name: 'john' };
  const nextState = changeName('jack')(state);
  assert.strictEqual(nextState.name, 'jack');
});

Async actions

For async action tests you need to instantiate the Store and provide mocked extra arguments.

import Store, { thunk } from 'repatch';
import * as assert from 'assert';
import { fetchUsers } from './actions';

const mockUsers = [{ username: 'john' }];
const mockApi = {
  getUsers: () => Promise.resolve(mockUsers)
}

// ...

it('fetchUsers', async () => {
  const state = { users: [] };
  const store = new Store(state)
    .addMiddleware(thunk.withExtraArgument({ api: mockApi }));
  await store.dispatch(fetchUsers());
  const nextState = store.getState();
  assert.deepEqual(nextState.users, mockUsers);
});

License

MIT

Community

https://twitter.com/repatchjs

Developed by

JayStack

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].