We have a standard react-redux setup but we have a plain old api service class that need some of the information that we store in our redux state. This service class is used by all of our components to access our backend.
I understand that I could pass the info from a component to our service class functions but I would have to do that everywhere.
I can't seem to find a solution for this. Has anyone else come across it?
Nathan
The general answer to that is "middleware". Either write a middleware that listens for custom actions you dispatch and makes the API calls itself, or something like redux-thunk that runs dispatched functions and injects the correct store functions.
http://chrispearce.co/redux-quick-hack-custom-thunk-apis/ explains the usefulness of thunks. Also, if you look at the Middleware page in my Redux addons catalog, you'll find numerous examples of centralizing interaction with various external services.
Yep, middleware is the way to go.
function myServiceMiddleware(myService) {
return ({ dispatch, getState }) => next => action => {
if (action.type == 'SOMETHING_SPECIAL') {
myService.doSomething(getState());
myService.doSomethingElse().then(result => dispatch({ type: 'SOMETHING_ELSE', result }))
}
return next(action);
}
}
// Usage:
import { createStore, applyMiddleware } from 'redux'
const serviceMiddleware = myServiceMiddleware(myService)
const store = createStore(reducer, applyMiddleware(serviceMiddleware))
馃憢 Helpful hint: the link to Mark @markerikson's article is:
Redux Hack: Custom Thunk APIs
Most helpful comment
Yep, middleware is the way to go.