2

I am trying to create a simple Redux middleware in my React Redux Electron app that uses Thunk and connected-react-router.

In myMiddleware.js, we need to access the Redux store and dispatch function to send some actions. However, getState and dispatch are undefined as shown in the code below.

What is the correct way to access both of them in a custom Redux middleware?

Github Repo: https://github.com/nyxynyx/accessing-store-dispatch-from-redux-middleware

middleware/myMiddleware.js

const myMiddleware = () => {
    return ({ getState, dispatch }) => {
        console.log(getState)       // undefined
        console.log(dispatch)       // undefined

        return next => action => {
            return next(action);
        }
    }
}

store.js

import { createStore, applyMiddleware, combineReducers, compose } from 'redux';
import { connectRouter, routerMiddleware, push } from 'connected-react-router';
import persistState from 'redux-localstorage';
import thunk from 'redux-thunk';

import myMiddleware from './middleware/myMiddleware';

export default function configureStore(initialState, routerHistory) {
    const router = routerMiddleware(routerHistory);

    const actionCreators = {
      push,
    };

    const reducers = {
      router: connectRouter(routerHistory),
    };

    const middlewares = [myMiddleware, thunk, router];

    const composeEnhancers = (() => {
      const compose_ = window && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__;
      if (process.env.NODE_ENV === 'development' && compose_) {
        return compose_({ actionCreators });
      }
      return compose;
    })();

    const enhancer = composeEnhancers(applyMiddleware(...middlewares), persistState());
    const rootReducer = combineReducers(reducers);

    return createStore(rootReducer, initialState, enhancer);
 }

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'connected-react-router';
import { createMemoryHistory } from 'history';
import routes from './routes';
import configureStore from './store';

const syncHistoryWithStore = (store, history) => {
  const { router } = store.getState();
  if (router && router.location) {
    history.replace(router.location);
  }
};

const initialState = {};
const routerHistory = createMemoryHistory();
const store = configureStore(initialState, routerHistory);
syncHistoryWithStore(store, routerHistory);

ReactDOM.render(
  <Provider store={store}>
    <ConnectedRouter history={routerHistory}>{routes}</ConnectedRouter>
  </Provider>,
  document.getElementById("root")
);

Using

  • connected-react-router@6.8.0
  • react-dom@16.13.1
  • react-redux@7.2.0
  • react-router-dom@5.1.2
  • react-router@5.1.2
  • react@16.13.1
  • redux-localstorage@0.4.1
  • redux-thunk@2.3.0
  • redux@4.0.5
  • Node v14.0.0
Nyxynyx
  • 61,411
  • 155
  • 482
  • 830

0 Answers0