Blog>
Snippets

Basic createReducer Usage for Single-Model Form

Show a simple usage of createReducer for handling state changes in a single-model form, including initial state and action handlers.
import { createReducer } from 'common/utils/reducerUtils';

// Action Types
const FORM_UPDATE_FIELD = 'form/updateField';

// Initial State for the Form
const initialFormState = {
    firstName: '',
    lastName: '',
    email: '',
};

// Action Handlers
const updateField = (state, action) => {
    const { field, value } = action.payload;
    state[field] = value;
};

// createReducer usage to handle form state updates
export default createReducer(initialFormState, {
    [FORM_UPDATE_FIELD]: updateField,
});
This code defines a simple reducer for handling state changes in a single-model form. It uses the `createReducer` utility function to update fields within the form's state. The `initialFormState` sets the shape of the form data. `FORM_UPDATE_FIELD` is the action type used to update any field in the form. The `updateField` function is an action handler that updates the state based on the field name and value provided in the action payload. The `createReducer` function then associates the action type with its handler.