Store: patchState is inconvenient for patching deep objects

Created on 14 May 2018  路  8Comments  路  Source: ngxs/store

I write a lot of boilerplate code like this

   const state = context.getState();
    context.patchState({
      someForm: {
        ...state.someForm,
        model: {
          ...state.someForm.model, 
          someFlag: false
        }
      }
    });

What I would like to have is something like this:

context.patchStatePath(['someForm', 'model', 'someFlag'], false)

There should be some helper for deep updates. For now, I write a lot of redux-style immutability stuff

core

Most helpful comment

I am working on a built-in immutability helper that will help in this regard. I'll keep you posted.

All 8 comments

I am working on a built-in immutability helper that will help in this regard. I'll keep you posted.

I think immer is a great solution for this kinda of stuff. Ideally your state isn't too deep so this isn't a problem but I agree.

Immer is exactly what I need.

@AlgoTrader

Currently we've got a lot of features that allow to reduce boilerplate code with ... object descruction:

@markwhitfeld

    deepMerge<T, S>(target: T, source: S): T & S {
        for (let [k, v] of Object.entries(source)) {
            if (!(k in target))
                target[k] = source[k];
            else if (v.constructor.name === 'Object')
                this.deepMerge(target[k], source[k]);
            else
                target[k] = source[k];
        }

        return target as T & S;
    }

Here's an Immer with NGXS article, hope this helps! https://blog.angularindepth.com/simple-state-mutations-in-ngxs-with-immer-48b908874a5e

broken link now :(

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sanchezcarlosjr picture sanchezcarlosjr  路  40Comments

amcdnl picture amcdnl  路  19Comments

amjmhs picture amjmhs  路  21Comments

xmlking picture xmlking  路  29Comments

Carniatto picture Carniatto  路  22Comments