angularngrxngrx-storengrx-store-4.0

changing the store state from component ngrx


I'm using selectors to select from the store

this.quizz = this.store.select(getSelectedQuizz);

I use the async pipe to read from this observable like this in the template

[*ngIf="quizz | async; let quizz"]

I only define the action and I didn't modify the reducer yet the template is a form when I save the form I dispatch an update action which is only defined in my actions with readonly but I notice that when ever I save the form and dispatch the action the store changed and I didn't specify any logic in the reducer to update the state for the update action yet I don't understand why.

enter image description here


Solution

  • You are using 2-way data-binding to bind store state to a form which is a bad practice.
    Don't touch anything inside store state except by reducers.

    Use spread operator to take a copy of state:

    this.store.select(getSelectedQuizz).subscribe(quizz => 
        this.quizzModel = {...quizz };
    );
    

    Also take care about deep copies. Use something like this.quizzModel = JSON.parse(JSON.stringify(quizz )); for deep copy.

    Hint: To avoid such kind of mistakes you can force state to be immutable. Check ngrx-store-freeze