A small reactive store with Proxy for a WordPress settings page
A settings page with dependent fields quickly turns into a tangle of event handlers: this checkbox shows three fields, that select changes a preview, the preview also depends on a number field. A reactive store puts the state in one object; the page code only changes values, and functions that subscribed to a value run when it changes. JavaScript’s Proxy makes such a store possible in 40 lines, without a framework.
Problem: A plugin settings page has 15 options that depend on each other. Every input has its own handler that updates other parts of the page, and after a few changes the page shows a preview that does not match the fields.
Solution: Keep the settings in a Proxy object whose set trap notifies subscribers of the changed key, bind the form inputs to the store with data-bind attributes, and write each dependent part of the page as one subscriber function.
The store
// js/settings-store.js
function haCreateStore( initialState ) {
const subscribers = new Map(); // key -> Set of callbacks
function subscribe( key, callback ) {
if ( ! subscribers.has( key ) ) {
subscribers.set( key, new Set() );
}
subscribers.get( key ).add( callback );
return () => subscribers.get( key ).delete( callback );
}
const state = new Proxy( { ...initialState }, {
set( target, key, value ) {
const old = target[ key ];
if ( Object.is( old, value ) ) {
return true;
}
target[ key ] = value;
subscribers.get( key )?.forEach( ( cb ) => cb( value, old ) );
subscribers.get( '*' )?.forEach( ( cb ) => cb( key, value, old ) );
return true;
},
} );
return { state, subscribe };
}
The set trap must return true; returning false throws a TypeError in strict mode (and ES modules are always strict). Object.is() skips notifications when the value did not change. The store is flat on purpose: only assignments to top-level keys are seen. state.list.push( item ) changes the array without calling set on the store, so arrays and objects are replaced instead: state.list = [ ...state.list, item ].
Bind the form
const { state, subscribe } = haCreateStore( window.haSettings.values );
document.querySelectorAll( '[data-bind]' ).forEach( ( input ) => {
const key = input.dataset.bind;
const read = () => {
if ( input.type === 'checkbox' ) return input.checked;
if ( input.type === 'number' ) return input.valueAsNumber;
return input.value;
};
const write = ( value ) => {
if ( input.type === 'checkbox' ) input.checked = !! value;
else input.value = value ?? '';
};
write( state[ key ] );
input.addEventListener( 'input', () => { state[ key ] = read(); } );
subscribe( key, write ); // keeps two inputs bound to the same key in sync
} );
<input type="checkbox" data-bind="advancedMode" name="ha_settings[advanced_mode]"> <select data-bind="currency" name="ha_settings[currency]">...</select> <input type="number" step="0.01" data-bind="basePrice" name="ha_settings[base_price]">
The inputs keep their name attributes, so the form is still submitted normally to options.php and the Settings API sanitizes the values on the server. The store only manages what the page shows before saving.
Dependent parts of the page
const renderAdvanced = ( enabled ) => {
document.querySelectorAll( '.ha-advanced' ).forEach( ( row ) => {
row.hidden = ! enabled;
} );
};
subscribe( 'advancedMode', renderAdvanced );
const format = () => new Intl.NumberFormat( document.documentElement.lang || 'en', {
style: 'currency',
currency: state.currency,
} ).format( state.basePrice || 0 );
const renderPreview = () => {
document.querySelectorAll( '[data-price-preview]' ).forEach( ( el ) => {
el.textContent = format();
} );
};
subscribe( 'currency', renderPreview );
subscribe( 'basePrice', renderPreview );
// run once for the initial values: the store only notifies on changes
renderAdvanced( state.advancedMode );
renderPreview();
Each subscriber describes one part of the page in terms of the state, and nothing else updates that part. Intl.NumberFormat takes care of the currency symbol and decimals instead of a hand-written '$' or '€'. textContent instead of innerHTML keeps values from the inputs from being interpreted as HTML.
Pass the initial values from PHP
add_action( 'admin_enqueue_scripts', 'ha_settings_assets' );
function ha_settings_assets( string $hook ): void {
if ( 'settings_page_ha-settings' !== $hook ) {
return;
}
$options = get_option( 'ha_settings', array() );
wp_enqueue_script( 'ha-settings', plugins_url( 'js/settings-store.js', __FILE__ ), array(), '1.0.0', true );
wp_add_inline_script( 'ha-settings', 'window.haSettings = ' . wp_json_encode( array(
'values' => array(
'advancedMode' => ! empty( $options['advanced_mode'] ),
'currency' => $options['currency'] ?? 'USD',
'basePrice' => (float) ( $options['base_price'] ?? 0 ),
),
) ) . ';', 'before' );
}
NOTE: A proxy is a different object than its target: state === target is false, and a WeakMap keyed with the target does not find the proxy. Keep the target private inside the store, as above, and always work with state. For bigger interfaces in the block editor, @wordpress/data is the store WordPress itself uses; the Proxy store is meant for classic admin pages without a build step.