Redux: Applying Redux Middleware

Dan Abramov
InstructorDan Abramov

Share this video with your friends

Send Tweet
Published 8 years ago
Updated 5 years ago

We will learn how to replace the middleware we wrote and the custom code we used to glue it together with the existing core and third party utilities.

[00:00] In the previous lesson, we figured out the contract that we want to use for our middleware functions. However, middleware wouldn't be very useful if everybody had to implement REV dispatch with middleware on their own. This is why I'm removing it, and instead I'm going to import a utility called apply middleware from Redux. I'm going back to my configure store function. I notice that I don't need the store right away. I can move the store creation after specifying the middleware.

[00:34] I can also remove my custom function, and instead I will create store with the middleware right away. I am passing the second argument to create store, which is the result of calling apply middleware with my middleware functions as positional arguments. This last argument to create store is called an enhancer, and it's optional. If you want to specify the persistent state, you need to do this before the enhancer. You can also keep the persistent state if you don't have.

[01:08] Many middlewares are available as NPM packages. Both the promise middleware and the logger middleware are no exceptions to this. I am opening up a terminal, and I'm running NPM install safe Redux promise, which is a middleware that implements the promise support.

[01:31] I can install a package called Redux Logger in the same way, which is similar to the logger middleware we wrote before, but it's more configurable. I am adding an input called lowercase promise that corresponds to the Redux promise middleware, and I'm inputting create logger from Redux Logger. It lets you configure the middleware before creating it. I won't pass any options to gather default configuration. Finally, since I don't need to reference the store anymore, I'll just return it directly from configure store.

[02:07] Let's recap how to apply Redux middleware. We use the function called apply middleware that we import from Redux. It accepts the middleware functions as positional arguments. For example, we could have written promise, create logger. However, we only want to apply the logger conditionally. If we're not running in the production environment, we will push the logger to the array of middlewares. We use the ES6 spread operator to pass every middleware as a positional argument to apply middleware.

[02:40] The apply middleware returns something called an enhancer. This is the optional last argument to create store. If you want to also supply the persistent state, you need to do this before the enhancer.