New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How can I access the store in non react components? #361
Comments
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: |
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 text was updated successfully, but these errors were encountered: