Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Redux store outside React when using next-redux-wrapper

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?

like image 304
CaribouCode Avatar asked Jun 28 '19 10:06

CaribouCode


People also ask

How do I access Redux store outside a react component?

You just need to export the store from the module where it created with createStore() . Also, it shouldn't pollute the global window object.

What does next Redux wrapper do?

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 with Redux?

Can I use Next. js with Redux? Yes! Here's an example with Redux and an example with thunk.

How do I use Redux dispatch outside component?

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.


1 Answers

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()),
);
like image 100
Scott Powell Avatar answered Sep 27 '22 17:09

Scott Powell