I have a NextJS React app that uses the next-react-wrapper (basically a HOC) on _app.tsx
like so:
_app.tsx
...
import withRedux from 'next-redux-wrapper';
class Page extends App<Props> {
...
}
export default withRedux(reduxStore)(Page);
store.ts
import { applyMiddleware, createStore } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension/developmentOnly';
import rootReducer from './reducer';
export default (
initialState: any = undefined,
) => createStore(
rootReducer,
initialState,
composeWithDevTools(applyMiddleware()),
);
I'm struggling to work out how to access the store outside of React such as in a simple helper function. My store.ts
file exports a makeStore
function which is needed (including the initial state) for the next-redux-wrapper HOC.
I could access the store in a React component and pass it to my helper functions as an argument each time but that seems messy.
Is there a way to access the store direct from non React helper function modules?
You just need to export the store from the module where it created with createStore() . Also, it shouldn't pollute the global window object.
This is where next-redux-wrapper comes in handy: It automatically creates the store instances for you and makes sure they all have the same state.
Can I use Next. js with Redux? Yes! Here's an example with Redux and an example with thunk.
If you need to dispatch actions from outside a React component, the same technique will work: import the store, then call store. dispatch() , passing the action you need to dispatch. It works the same as the dispatch function you get from props via react-redux's connect function.
It may not be preferable, but the store can be accessed from the window using a storeKey
. The default key is __NEXT_REDUX_STORE__
and using it look like this:
window.__NEXT_REDUX_STORE__.getState()
Here's where that happens
The key (storeKey
) can be changed in the second options parameter passed to the withRedux function parameter. For your implementation it looks like this:
export default (
initialState: any = undefined,
{ storeKey: 'whateveryouwant' } // the name on the exposed store variable
) => createStore(
rootReducer,
initialState,
composeWithDevTools(applyMiddleware()),
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With