Reputation: 1689
I am using NGXS as my state management library. I have a users state and a selector to get list of users. I also have a component where I want to update user's name. The way I want to do this is to copy the users list that I get from the selector observable and use ngModel with inputs.
Here is an example of what I am trying to achieve.
And a snipped of my state selector
@Selector()
static getAll(state: User[]) {
return [...state];
}
The problem is modifying the data received form the selector is modifying the actual state even without dispatching an Action. I understand its because I am mutating the objects that I get from the state directly but aren't selectors supposed to be readonly?
So the questions I have are
return state.map(user=>Object.assign({}, user))
doesnt work. Is is the correct way to define a Selector?Upvotes: 1
Views: 1003
Reputation: 1501
To answer your questions:
Selectors should be kept immutable, but there isn't anything in NGXS that actually enforces that. So, no, they are not. It is up to you to keep it immutable, should you choose to do so.
What doesn't work?
Probably not.
It seems like you're thinking that whatever you get back from your selector is readonly... it's not. In dev mode it will complain and say that it is readonly, but in production it will let you mutate to your hearts content. My suspicion is you're mutating what your selector returns in your component, or rather just "up stream" (like even in another selector).
So, I just looked at your example in stackblitz. You are indeed mutating with the two-way data binding: [(ngModel)]="user.name"
. You need to fix that.
Upvotes: 2