You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Befuddled about this middleware thing? Don't worry, we all are the first time we see it. Let's peel it back a little bit and destructure what's going on. That `loggingMiddleware` description above could be rewritten like the following:
To _apply_ middleware, we can call this `applyMiddleware()` function in the `createStore()` method. In our `src/redux/configureStore.js` file, let's update the store creation by adding a call to `applyMiddleware()`:
158
160
159
161
```javascript
160
-
conststore=createStore(
161
-
rootReducer,
162
-
initialState,
163
-
applyMiddleware(
164
-
apiMiddleware,
165
-
loggingMiddleware,
166
-
)
167
-
);
162
+
// ...
163
+
importloggingMiddlewarefrom"./loggingMiddleware";
164
+
// ...
165
+
conststore=createStore(
166
+
rootReducer,
167
+
initialState,
168
+
applyMiddleware(
169
+
loggingMiddleware,
170
+
)
171
+
);
168
172
```
169
173
170
174
Now our middleware is in place. Open up the console in your browser to see all the actions that are being called for this demo. Try clicking on the `Update` button with the console open...
@@ -176,24 +180,26 @@ As we've seen, middleware gives us the ability to insert a function in our Redux
176
180
We want to write a middleware function that can handle API requests. We can write a middleware function that listens only to actions corresponding to API requests. Our middleware can "watch" for actions that have a special marker. For instance, we can have a `meta` object on the action with a `type` of `'api'`. We can use this to ensure our middleware does not handle any actions that are not related to API requests:
177
181
178
182
```javascript
183
+
// src/redux/apiMiddleware.js
179
184
constapiMiddleware=store=>next=>action=> {
180
185
if (!action.meta||action.meta.type!=='api') {
181
186
returnnext(action);
182
187
}
183
188
184
189
// This is an api request
185
190
}
191
+
exportdefaultapiMiddleware
186
192
```
187
193
188
194
If an action does have a meta object with a type of `'api'`, we'll pick up the request in the `apiMiddleware`.
189
195
190
-
Let's convert our `updateTime()` actionCreator to include these properties into an API request. Let's open up the `currentTime` redux module we've been working with (in `src/redux/currentTime.js`) and find the `fetchNewTime()` function definition.
196
+
Let's convert our `fetchNewTime()` actionCreator to include these properties into an API request. Let's open up the `actionCreators` redux module we've been working with (in `src/redux/actionCreators.js`) and find the `fetchNewTime()` function definition.
191
197
192
198
Let's pass in the URL to our `meta` object for this request. We can even accept parameters from inside the call to the action creator:
0 commit comments