Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I store objects in the store (ngrx, ngxs) that have methods

I understand that the Redux pattern requires only plain object to be stored in the Store (this is logical and understandable). However, in the application I would like to use objects that have some functionality, eg methods such as: "hasParent", "isReadonly", "isValid", which are calculated.

Although, for example, ngrx does not prohibit the storing of such objects, this can lead to many problems

How should I deal with this objects storing problem? I have two ideas: A) -before I save the object to the store, I serialize the object into plain data -when reading from the store, I map plain data to the object (using the mapper or "manually" (with object constructor and setters)) B) I resign from using class / objects, I use only plain data and I move the hasParent, isReadonly, isValid methods to the helpers / services.

None of these solutions is free from disadvantages :(. But which solution seems to be better? Maybe there are other ways to deal with the above problem?

like image 819
Wixer Avatar asked Sep 13 '25 05:09

Wixer


1 Answers

How do I store objects in the store (ngrx, ngxs) that have methods --> you don't! You store a state in the store. Functions don't belong to a state. (You seem to understand this in the question details, but I want to point this out again)

As for the functions you need:

  • readonly: in most cases this is a boolean flag on the object. So I don't know why you want to use it as a function. If read only is depending e.g. on the user role or other outside factors, move it into a "utility function" and don't store it with the store state. You want to keep keep the state as small as possible.
  • isValid: why would you store invalid data inside the store, which is then potentially used by another component? Personally I would consider data inside the store always as valid, but maybe there is a use case.
  • hasParent: I see this more as "parentId", from which you can get the actual parent object with a helper method. But without knowing your structure I cannot say.

Before thinking to much about it, ask yourself: Do I really need a store for this. Wouldn't a service be enough. A store is the hottest things right now, but most applications don't need it! Don't use it just because everyone is talking about it!

like image 157
Stefan Avatar answered Sep 15 '25 18:09

Stefan