Blog>
Snippets

Extending the WordPress Data Store with Custom Middlewares

Showcase how to extend the WordPress Data Store with custom middleware for logging state changes.
import { createReduxStore, register } from '@wordpress/data';

// Custom logging middleware
const loggerMiddleware = store => next => action => {
    console.log('Dispatching action:', action);
    console.log('Current state:', store.getState());
    const result = next(action);
    console.log('Next state:', store.getState());
    return result;
};

// Define your store's reducer
const reducer = (state = {}, action) => {
    // Handle your actions and update state accordingly
    return state;
};

// Create the store with the logging middleware
const store = createReduxStore('plugin/custom-store', {
    reducer,
    middleware: [loggerMiddleware]
});

// Register the store
register(store);
This JavaScript code snippet creates a custom WordPress data store with a logging middleware. The middleware logs every action dispatched to the store along with the state before and after that action. The 'createReduxStore' function is used to create the store with the custom 'reducer' and 'loggerMiddleware'. Finally, the 'register' function is used to register the custom store with the WordPress data module.