Creating Parameterized Action Creators for Middleware
Create a parameterized action creator function that generates actions with dynamic payloads and meta info, which can be used within middleware to tailor responses and side-effects based on action parameters.
import { createAction } from '@reduxjs/toolkit';
// Define a parameterized action creator
const fetchData = createAction('data/fetch', function prepare(query, page) {
return {
payload: {
query: query, // Dynamic payload based on parameters
page: page
},
meta: {
timestamp: Date.now() // Meta info, such as current timestamp
}
};
});
This code creates a parameterized action creator using Redux Toolkit's createAction. The action creator is named fetchData and it takes two parameters: query and page. It returns an action object with a dynamic payload that includes the query and page, and also includes meta information like the current timestamp.
import { isAnyOf } from '@reduxjs/toolkit';
// In your middleware
const myMiddleware = store => next => action => {
if (isAnyOf(fetchData.match, anotherActionCreator.match)(action)) {
const { type, payload, meta } = action;
// React to the action with its payload and meta data
// ... perform side effects or conditional logic based on the action
}
// Always call the next function to pass the action along the middleware chain
return next(action);
};
This code implements middleware using the parameterized action creator defined earlier. It demonstrates how to use Redux Toolkit's isAnyOf utility function with the match method of action creators to handle specific action types. When an action matches, the middleware can extract the payload and meta information from the action and perform side effects or other logic before passing the action along to the next middleware or reducer.