Skip to content
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

Closed
nmaves opened this issue Apr 20, 2016 · 3 comments
Closed

How can I access the store in non react components? #361

nmaves opened this issue Apr 20, 2016 · 3 comments
Labels

Comments

@nmaves
Copy link

nmaves commented Apr 20, 2016

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

@markerikson
Copy link
Contributor

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.

@gaearon
Copy link
Contributor

gaearon commented Apr 20, 2016

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))

@StevenBlack
Copy link

👋 Helpful hint: the link to Mark @markerikson's article is:
Redux Hack: Custom Thunk APIs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants