0

I have a large react-redux based application in development. I'd like to add some utility functions to a js script that does not contain a react component to "connect" to. How do I access the state in react-redux without a component? Neither mapStateToProps nor mapDispatchToProps are available - do I need to export the state object from the top-level index.js file? Seems dangerous.

Suggestions welcome!

JB

Omortis
  • 1,334
  • 19
  • 44
  • https://stackoverflow.com/questions/38460949/what-is-the-best-way-to-access-redux-store-outside-a-react-component – JakeD Jul 20 '17 at 17:29
  • @Jaked222 - I don't want to export or import the store (although this is all client side so I could). Also, per Abramov's suggestion linked from that page, I was considering simply creating a component with an empty render() method but was looking for a better solution... – Omortis Jul 20 '17 at 17:50
  • What is "connect" mean in your context? You should try refs. – fungusanthrax Jul 20 '17 at 19:00
  • `import { connect } from 'react-redux';` – Omortis Jul 20 '17 at 19:13

3 Answers3

1

Workaround way: Import your store inside the scope of your utility functions.

Importing the store (which you would have created while setting up your app) will provide dispatch and getState methods using which you can get access to your state vars.

src/store.js

import ReduxThunk from 'redux-thunk';
import { createStore, applyMiddleware } from 'redux';
import logger from 'redux-logger';
import reducers from './reducers';

var middleware = [ReduxThunk];
if (process.env.NODE_ENV !== 'production') {
  middleware = [...middleware, logger];
}

const createStoreWithMiddleware = applyMiddleware(...middleware)(createStore);

export default createStoreWithMiddleware(reducers);

helper.js

import store from "./store"
const { var1, var2 } = store.getState();
Saurish Kar
  • 576
  • 7
  • 13
-1

The phrasing of your question is just a bit odd. If you're asking about accessing the store in utility functions that aren't related to any components, then you aren't using React-Redux to do so :)

In this case, you would either import the store directly into those utility function modules, or call the functions from some scope that does have access to store capabilities (such as a thunk action creator that was dispatched from a connected component).

There's a related Redux FAQ entry on why you should generally prefer to not import the store directly.

markerikson
  • 63,178
  • 10
  • 141
  • 157
  • Yeah I don't want to import the store directly as I think that's a bad idea. I am indeed calling the functions and sending them data from store-aware components but I wanted to avoid all that parameter passing if possible... – Omortis Jul 20 '17 at 16:22
-1

No really graceful way to do it. Long argument list it is.

Omortis
  • 1,334
  • 19
  • 44