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")
Please, read introduction to thunks in Redux. Execue just another way to run and test thunks(effects).
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)
}
An effect is a thunk that called by dispatch
.
const effect = (a, b) => (dispatch, getState) => {
return a + b
}
store.dispatch(effect, 1, 2) // 3
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 []
}
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 }),
),
)