Skip to content

Proposal: Add support for onChange callbacks #72

@unadlib

Description

@unadlib
Owner

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.

Activity

atsjo

atsjo commented on Jan 7, 2025

@atsjo

Just migrated to mutative days ago, and this feature is EXACTLY what i need. When editing data in my UI I currently have an internal custom "proxyObserver" wrapping a clone of my data and giving me onChange callbacks (for showing if data is changed). But with this I can replace my proxyObserver and also generate patches and minimize the mutations in the changed data.

unadlib

unadlib commented on Jan 7, 2025

@unadlib
OwnerAuthor

hi @atsjo, I may start implementing this API soon.

atsjo

atsjo commented on Jan 7, 2025

@atsjo

Made it work with the current version by wrapping the draft in my custom proxyObserver, so using double proxy for the state...
Will I get into problems if never finalizing a draft, but just dropping the reference in js, like memory leaks or performance?

unadlib

unadlib commented on Jan 8, 2025

@unadlib
OwnerAuthor

These drafts are not finalized, which means they might require shallow copying under the immutable mechanism, and the draft instances will not be garbage collected.

I don’t really recommend doing this. It seems like the proxyObserver you mentioned is probably an observer for mutable types. I’ve previously implemented a transactional mutable state update library https://github.com/mutativejs/mutability, though I’m not sure if it’s what you’re looking for.

atsjo

atsjo commented on Jan 8, 2025

@atsjo

ok, thanks for the info!

I normally use it like a normal producer, but also have a forms based ui bound to a json structure, where this is used to generate the diff from last saved state. When saving I generate the diff via finalize, but I didn't bother finalizing the draft if the user cancels the edit session...

My proxyObserver is just for getting callbacks when users change anything via the ui, so I can show if there are modifications and show the save button... If I could get a callback on every change from mutative I wouldn't need it...

I'll just ensure finalize is called also when users cancels the changes....

unadlib

unadlib commented on Jan 8, 2025

@unadlib
OwnerAuthor

ok, thanks for the info!

I normally use it like a normal producer, but also have a forms based ui bound to a json structure, where this is used to generate the diff from last saved state. When saving I generate the diff via finalize, but I didn't bother finalizing the draft if the user cancels the edit session...

My proxyObserver is just for getting callbacks when users change anything via the ui, so I can show if there are modifications and show the save button... If I could get a callback on every change from mutative I wouldn't need it...

I'll just ensure finalize is called also when users cancels the changes....

hi @atsjo ,

I suggest using mutative in this scenario like this. This ensures drafts are discarded and minimizes the risk of memory leaks.

import { create, original, rawReturn } from 'mutative';

const nextState = create(initState, (draft) => {
  // some logic about `shouldBeChanged`
  if (!shouldBeChanged) {
    return rawReturn(original(draft));
  }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @atsjo@unadlib

        Issue actions

          Proposal: Add support for onChange callbacks · Issue #72 · unadlib/mutative