Reputation: 4014
I am creating a chat application with Redux + Middleware and would like to use middleware to store objects in a local storage object whenever an action of ADD_MESSAGE
is dispatched:
export function storageMiddleware(store) {
return next => action => {
const result = next(action);
if (action.type === "ADD_MESSAGE") {
// Add to my storage object here
}
return result;
};
}
If apply my middleware like so:
const store = createStore(
reducer,
applyMiddleware(thunk, chatMiddleware)
)
I would like to pass in my storage object, storage
, but can't find anywhere in the documentation how to pass in additional arguments. How can I do this?
Upvotes: 5
Views: 3036
Reputation: 67469
You need to add one more level of function nesting to make it work. redux-thunk
does the same thing:
// Middleware definition
function createThunkMiddleware(extraArgument) {
return ({ dispatch, getState }) => next => action => {
if (typeof action === 'function') {
return action(dispatch, getState, extraArgument);
}
return next(action);
};
}
const thunk = createThunkMiddleware();
thunk.withExtraArgument = createThunkMiddleware;
// Middleware usage
const store = createStore(
reducer,
applyMiddleware(thunk.withExtraArgument(api))
)
Upvotes: 6