Search code examples
angularngxs

Class based object instances for state in NGXS


NGXS Style Guide has a point:

It is not recommended to add Class based object instances to your state because this can lead to undefined behavior in the future.

e.g.

//== This is NOT recommended:
ctx.setState((state: Todo[]) => state.concat(new Todo(action.title)));

//== This is recommended
state.concat({ title: action.title, isCompleted: false })

Why creating class instance with new is not recommended?


Solution

  • Because those created objects have multiple properties, like functions, constructor, maybe private properties and so on ... you dont want to save those properties too!

    You should have an export-function in your Todo-class:

    interface TodoModel {
      /* your properties you want to take care of! */
    }
    
    class Todo implements TodoModel {
      export(): TodoModel {
      }
    
      import(model: TodoModel) {
      }
    }