concept analytic middleware in category react

appears as: The alytics middleware, nalytics middleware, alytics middleware
Redux in Action

This is an excerpt from Manning's book Redux in Action.

Parsnip now has its first custom middleware, but you’ve only scratched the surface. Let’s explore another common use case for middleware: sending analytics events. The analytics middleware will be similar to the logger, but we’ll introduce a new concept along the way: the meta property, which allows you to attach additional data to an action object. Then, in the middleware you can watch for the meta property on incoming actions and do work if the right conditions are satisfied.

Listing 5.4. Implementing the analytics middleware – src/middleware/index.js
const analytics = store => next => action => { if (!action || !action.meta || !action.meta.analytics) { #1 return next(action); #2 } const { event, data } = action.meta.analytics; #3 fakeAnalyticsApi(event, data) .then(resp => { console.log('Recorded: ', event, data); #4 }) .catch(err => { console.error( #5 'An error occurred while sending analytics: ', err.toString(), ); }); return next(action); #6 }; function fakeAnalyticsApi(eventName, data) { return new Promise((resolve, reject) => { resolve('Success!'); }); } export default analytics; #1 Checks whether the action wants to use the analytics middleware #2 If the right action properties aren’t found, move on to the next middleware. #3 Uses destructuring to get the event name and any associated metadata #4 Logs the event being recorded successfully #5 Logs an error if necessary #6 Moves on to the next middleware !@%STYLE%@! {"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":1,\"ch\":64},{\"line\":1,\"ch\":66}],[{\"line\":29,\"ch\":0},{\"line\":29,\"ch\":2}],[{\"line\":2,\"ch\":64},{\"line\":2,\"ch\":66}],[{\"line\":30,\"ch\":0},{\"line\":30,\"ch\":2}],[{\"line\":5,\"ch\":64},{\"line\":5,\"ch\":66}],[{\"line\":31,\"ch\":0},{\"line\":31,\"ch\":2}],[{\"line\":9,\"ch\":64},{\"line\":9,\"ch\":66}],[{\"line\":32,\"ch\":0},{\"line\":32,\"ch\":2}],[{\"line\":12,\"ch\":64},{\"line\":12,\"ch\":66}],[{\"line\":33,\"ch\":0},{\"line\":33,\"ch\":2}],[{\"line\":18,\"ch\":64},{\"line\":18,\"ch\":66}],[{\"line\":34,\"ch\":0},{\"line\":34,\"ch\":2}]]"} !@%STYLE%@!