Last Updated on March 21, 2021 by Neil Murray
@wordpress/data is a wrapper of Redux in WordPress environment. It is used as data management between functions or components. It serves as a hub to manage application state for both plugins and WordPress itself.
By using the @wordpress/data package as a hub with tools to manage data, states will be shared and managed directly between components.
Our previous approach was by passing states and manage functions to child components. This is a commonly used approach suitable for relatively simple applications.
As CF7 Skins Add-ons (particularly Logic) are added together into Visual, this will add extra complexity. Visual states and functions will grow and become harder to maintain.
With @wordpress/data we no longer need to pass props into child components, and child components can read and write data easily.
Action #
An action is a function that optionally accepts arguments and returns an action object to dispatch to the reducer.
Example:
const actions = {
myAction( label ) {
return {
type: 'MY_ACTION',
label,
};
},
}
Reducer #
A reducer is a function accepting the previous state and action as arguments and returns an updated state value. Current state read-only. The function should use a copy of current state, modify it and return only the modified state.
Example:
const reducer = ( state, action ) => {
if ( action.type === 'MY_ACTION' ) {
const rowInfo = state.rowInfo.slice(); // make a copy
rowInfo.cf7sLabel = action.label; // update label
return {
...state,
rowInfo,
};
}
}
Selector #
A selector is a function which accepts state and optional arguments and returns some value from state.
Example:
const selectors = {
getRowInfo( state ) {
return state.rowInfo;
},
}
Registering Store #
We need a store after creating action, reducer and selector. We use registerStore and passing them as parameters for registration.
const { registerStore, } = { ...window.wp.data };
registerStore( 'cf7svisual', {
reducer,
actions,
selectors,
} );
We only need to register store once in top level component and child components can use actions and selector after registration to read and write data.
Heading #
Data contains a reducer, selector and action which can be found in src/visual/data/ directory.
Further Reading
Notes
Add notes here
Save all Images to Dropbox – use ..\Dropbox\Development\Development Guidelines\CF7 Skins Code\CF7 Skins Visual Code\@wordpress-data\