Introduction
Redux Thunk middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met. The inner function receives the store methods dispatch and getState as parameters.
Installation of Thunker
npm install --save redux-thunk
What’s a thunk?!
A thunk is a function that wraps an expression to delay its evaluation or execution.
// calculation of 1 + 5 is immediate
// x === 6
let x = 1 + 5;
// calculation of 1 + 5 is delayed
// foo can be called later to perform the calculation
// foo is a thunk!
let foo = () => 1 + 5;
Then, to enable Redux Thunk, use applyMiddleware():
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';
// Note: this API requires redux@>=3.1.0
const store = createStore(
rootReducer,
applyMiddleware(thunk)
);
Commenti