Implementing a Selector in the WordPress Data Module
Craft a selector function to retrieve a piece of state from the WordPress store, such as a user's display name.
const { registerStore, select } = wp.data;
// Define the store name
const STORE_NAME = 'my-custom-store';
// Register the store
registerStore(STORE_NAME, {
reducer() {
// Define the initial state
return {
currentUser: null // Initial state for current user data
};
},
selectors: {
// Define a selector to retrieve the current user's display name
getCurrentUserDisplayName(state) {
return state.currentUser ? state.currentUser.displayName : null;
}
},
// ... actions, resolvers, etc.
});
// Use the selector
const displayName = select(STORE_NAME).getCurrentUserDisplayName();
console.log(displayName);
Registers a custom store with an initial state containing the currentUser and a selector to retrieve the current user's display name. The store is named 'my-custom-store'. After registering the store, the selector 'getCurrentUserDisplayName' is used to retrieve and log the display name.