Skip to content

reconcile: support "merge" in objects #2475

@hyperknot

Description

@hyperknot

A common pattern I believe is to reconcile partial state updates in stores.

For example, part of a store is synced to a backend, so after a push-to-backend operation, it returns an up-to-date data for part of the store values. Other values, like UI related ones are not included in this data.

Passing this raw data into setStore works, but triggers unnecessary updates. It triggers every single key's update, which is an array or object.

Here is my 1st idea to tackle this: running reconcile in a for loop on each 1st level key:

for (const key of Object.keys(data)) {
  this.setState(key as any, reconcile(data[key as keyof typeof data]))
}

This works, and when put in a batch() should be performant. Quite a lot of code, so asks for a wrapper function, but should be good.

My 2nd idea is this:

this.setState(reconcile({ ...this.state, ...data }))

This also works. If I understand correctly, it's a tiny bit slower, but the slowness happens in the pure JS code, not in the actual UI updates, so it should still be fast.

When I looked at the source code for reconcile and found that it supports merge, but only for arrays.

I'd like to recommend to add support for merge in objects. To make sure that this does not modify the array behaviours in sub-keys, it should be called something different, "partial" probably.

I believe it'd be as simple as turning off the delete loop in the first level of applyState.

Please tell me if I'm not correct in this. Isn't this a common pattern when using stores?

How do you normally solve this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions