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: traverse return value and finalize drafts by default unless use rawReturn() #9

Closed
unadlib opened this issue Mar 14, 2023 · 1 comment
Labels
enhancement New feature or request

Comments

@unadlib
Copy link
Owner

unadlib commented Mar 14, 2023

To make the migration from Immer to Mutative smoother, we consider return values that are all traversed and finalized by default. For return values without mixed drafts, rawReturn() can be used to improve performance, and we will hint at such an optimization with checking mixed drafts in strict mode.

@unadlib unadlib changed the title Proposal: traverse return value and finalize drafts by default unless use safeReturn() Proposal: traverse return value and finalize drafts by default unless use rawReturn() Mar 26, 2023
@unadlib
Copy link
Owner Author

unadlib commented Mar 26, 2023

For return values that do not contain any drafts, you can use rawReturn() to wrap this return value to improve performance. It ensure that the return value is only returned explicitly.

const baseState = { id: 'test' };
const state = create(baseState as { id: string } | undefined, (draft) => {
  return rawReturn(undefined);
});
expect(state).toBe(undefined);

You don't need to use rawReturn() when the return value have any draft.

const baseState = { a: 1, b: { c: 1 } };
const state = create(baseState, (draft) => {
  if (draft.b.c === 1) {
    return {
      ...draft,
      a: 2,
    };
  }
});
expect(state).toEqual({ a: 2, b: { c: 1 } });
expect(isDraft(state.b)).toBeFalsy();

If you use rawReturn(), we recommend that you enable strict mode in development.

const baseState = { a: 1, b: { c: 1 } };
const state = create(
  baseState,
  (draft) => {
    if (draft.b.c === 1) {
      return rawReturn({
        ...draft,
        a: 2,
      });
    }
  },
  {
    strict: true,
  }
);
// it will warn `The return value contains drafts, please don't use 'rawReturn()' to wrap the return value.` in strict mode.
expect(state).toEqual({ a: 2, b: { c: 1 } });
expect(isDraft(state.b)).toBeFalsy();

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

1 participant