Blog>
Snippets

Defining a Redux-Style Action in WordPress

Create a simple action for updating a user's custom setting in a WordPress Redux store.
import { createAction } from '@wordpress/data';

// Define the action type
const UPDATE_USER_SETTING = 'UPDATE_USER_SETTING';

// Define the action creator using createAction utility
export const updateUserSetting = createAction(
    UPDATE_USER_SETTING,
    (settingName, settingValue) => ({ settingName, settingValue })
);
This snippet uses the 'createAction' utility from '@wordpress/data' to define an action creator for updating a user's custom setting. The 'UPDATE_USER_SETTING' is the type of action. The 'updateUserSetting' function is the action creator that takes the setting name and value as arguments and constructs an action object.