Open
Description
Proposal
I propose adding support for a mutation callback feature to trigger state change events. This would allow developers to provide a callback function to track mutations (e.g., state changes, patches, and inverse patches) during a state update.
Use Case
This feature would be especially helpful for:
- Logging state changes for debugging or analytics purposes.
- Integrating with tools that depend on patch operations, such as undo/redo systems.
- Reacting to state changes in a controlled manner without manually diffing the state.
Suggested API
Here’s an example of how this could work:
import { create } from 'mutative';
const state = { count: 0, items: [] };
const draft = create(state, {
onChange: (state, patches, inversePatches) => {
console.log('State updated:', state);
console.log('Patches:', patches);
console.log('Inverse Patches:', inversePatches);
},
enablePatches: true,
});
draft.count += 1; // The `onChange` callback is executed here with `state`, `patches`, and `inversePatches`.
Callback Function Signature:
onChange?: (state: T, patches?: Patch[], inversePatches?: Patch[]) => void;
Parameters:
- state: The updated state after the mutation.
- patches: An array of patches representing the changes made.
- inversePatches: An array of patches that can revert the changes.
Implementation Notes
- The onChange function would be executed every time a mutation occurs.
- It would receive the following parameters:
- state: The updated state.
- patches: A list of patches representing the changes made to the state.
- inversePatches: A list of patches that can revert the changes.
This API would be backward-compatible and opt-in, ensuring it does not affect existing users who do not need the onChange functionality.
Benefits
- Enhances the usability of Mutative for advanced use cases like undo/redo or logging.
- Keeps the core principles of Mutative intact while extending its functionality.