immer icon indicating copy to clipboard operation
immer copied to clipboard

isModified helper

Open Mangatt opened this issue 1 year ago • 1 comments

🚀 Feature Proposal

It would be great to have isModified helper, much like isDraft or current functions.

Motivation

More efficient updates of derived data in draft. Immer currently do have all necessary information, in it's essence it is stripped down version of current.

Can this be solved in user-land code?

It can be solved in following ways:

  1. You can compare current with original in draft - but that's unnecessarily expensive for simple yes/no query
  2. You can finishDraft, compare with original, then createDraft again if necessary

Example

produce(deeplyNestedObject, (draft) => {
	performOpaqueDeeplyNestedUpdates(draft)
	
	if(isModified(draft.item)){
		draft.item.modifiedOn = new Date()
	}
})

Mangatt avatar Jan 03 '25 07:01 Mangatt

FWIW this could be done with a bit of copy-paste out of the library source to read from the internal state value:

export let isObjectish = (target: any) => typeof target === "object"

export let getProxyDraft = <T extends any>(value: T): ImmerState | null => {
	if (!isObjectish(value)) return null
	return (value as {[DRAFT_STATE]: any})?.[DRAFT_STATE]
}

export let isModified = (target: any) => !!getProxyDraft(target)?.modified_

markerikson avatar Oct 30 '25 23:10 markerikson