Skip to content
This repository has been archived by the owner on Sep 16, 2020. It is now read-only.

sergeysova/redux-execute

Repository files navigation

redux-execute Maintainability Build Status Coverage Status

Readme

Installation

Note: redux-execute requires redux@^4.0.0

npm install --save redux-execute

ES modules:

import { createExecue } from "redux-execute"

CommonJS:

const { createExecue } = require("redux-execute")

Why do I need this?

Please, read introduction to thunks in Redux. Execue just another way to run and test thunks(effects).

Motivation

Redux Execue middleware allows you to write "action creators" that return function instead of an action. These action creators are called effects. The effect can be used to delay the dispatch an action, or to dispatch another effect, or to dispatch only if a certain condition is met. The inner function receives the store methods dispatch and getState as parameters.

An action creator that returns a function to perform asynchronous dispatch:

const setValue = (value) => ({
  type: "SET_VALUE",
  payload: { value },
})

const setValueWithDelay = (value) => (dispatch) => {
  setTimeout(() => {
    // classic dispatch action
    dispatch(setValue(value))
  }, 1000)
}

Effect that dispatch another effect:

const incrementWithDelay = () => (dispatch, getState) => {
  const { value } = getState()

  // Just pass effect and all arguments as arguments of dispatch
  dispatch(setValueWithDelay, value + 1)
}

What is an effect?

An effect is a thunk that called by dispatch.

const effect = (a, b) => (dispatch, getState) => {
  return a + b
}

store.dispatch(effect, 1, 2) // 3

See also

Composition

Any return value from the inner function of effect will be available as the return value of dispatch itself. This is convenient for orchestrating an asynchronous control flow with effects dispatching each other and returning Promises to wait for each other's completion.

const requestGet = (url) => () =>
  fetch(`/api${url}`).then((response) => response.json())

const userPostsFetch = (userId) => async (dispatch) => {
  const user = await dispatch(requestGet, `/users/${userId}`)

  if (user.isActive) {
    return dispatch(requestGet, `/users/${userId}/posts`)
  }

  return []
}

Logger

Redux Execue has logger out of the box. You can combine it with redux-logger:

import { createStore, applyMiddleware } from "redux"
import { createLogger } from "redux-logger"
import { createExecue } from "redux-execute"

import { rootReducer } from "./reducers"

const store = createStore(
  rootReducer,
  applyMiddleware(
    createExecue({ log: true }),
    createLogger({ collapsed: true }),
  ),
)