Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: Add support for onChange callbacks #72

Open
unadlib opened this issue Nov 25, 2024 · 6 comments
Open

Proposal: Add support for onChange callbacks #72

unadlib opened this issue Nov 25, 2024 · 6 comments
Labels
enhancement New feature or request

Comments

@unadlib
Copy link
Owner

unadlib commented Nov 25, 2024

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.
@unadlib unadlib added the enhancement New feature or request label Nov 25, 2024
@atsjo
Copy link

atsjo commented Jan 7, 2025

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
Copy link
Owner Author

unadlib commented Jan 7, 2025

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

@atsjo
Copy link

atsjo commented Jan 7, 2025

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
Copy link
Owner Author

unadlib commented Jan 8, 2025

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
Copy link

atsjo commented Jan 8, 2025

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
Copy link
Owner Author

unadlib commented Jan 8, 2025

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
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants