Search code examples
reactjsreduxmiddleware

Passing construction parameters to redux middleware


I was curious if there is a way to pass a parameter to a middleware without retrieving it from the state. What I want to do is to pass a generic function that we are using that determines if the user is authenticated or not. So rather than retreiving the authentication information from the state which will be code duplication, I want to pass isAuthenticated function to the middleware.

I don't think this is implemented natively in applyMiddleware framework but maybe someone has a work around for this situation.


Solution

  • Ok the right way to do this turned out to be a wrapper function that will wrap the actual middleware function

    export const middlewareFunction = (store) => (next) => (action) => {
        do some stuff with something...
    }
    

    If this is your actual middleware function, than you should be applying the middleware as

    applyMiddleware(middlewareFunction);
    

    What you should be doing to pass a parameter is to implement a function like

    export const middlewareWrapper = (args) => {
        do some stuff with your args 
        return (state) => (next) => (action) => {
            do more stuff with your args and actions
        }
    } 
    

    With this syntax you can apply the middleware as :

    applyMiddleware(middlewareWrapper(args));