Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add enhancer to redux store after createStore()

Tags:

redux

Is this possible?

I'm using redux store in an IoC environment and want to add middleware to the store after it is created.

e.g.:

class MyApp {
  store = createStore(...);
}

let app = new MyApp();

// later on
import thunk from 'redux-thunk';
app.store.addEnhancer(thunk);
like image 797
unional Avatar asked Jul 07 '16 08:07

unional


People also ask

Is createStore deprecated?

Solution: The createStore is deprecated.

What does createStore do in Redux?

createStore(reducer, [preloadedState], [enhancer]) Creates a Redux store that holds the complete state tree of your app. There should only be a single store in your app.

What is store enhancer in Redux?

Store enhancers are a formal mechanism for adding capabilities to Redux itself. Most people will never need to write one. To use middleware in Redux, we use the applyMiddleware() function exported by the Redux library. applyMiddleware is itself a store enhancer that lets us change how dispatch() works.

How can the initial state be passed to store using the createStore function?

There are two main ways to initialize state for your application. The createStore method can accept an optional preloadedState value as its second argument. Reducers can also specify an initial value by looking for an incoming state argument that is undefined , and returning the value they'd like to use as a default.


1 Answers

I have created a function to do this. If redux think this is valuable, I can do a PR.

This is code that tailored to my module. The actual one add to PR will look a bit different.

addMiddleware(middleware: Middleware) {
  const middlewareAPI: MiddlewareAPI<any> = {
    getState: this.getState,
    dispatch: (action) => this.dispatch(action)
  };

  this.dispatch = compose(middleware(middlewareAPI))(this.dispatch);
}
like image 190
unional Avatar answered Jan 03 '23 01:01

unional