w11k / Tydux

Type safe state management for web applications
Apache License 2.0
36 stars 4 forks source link

How do I change the state in an async mutator? #4

Closed pburgmer closed 7 years ago

pburgmer commented 7 years ago

I have following mutator method

loadTrainings() {
    this.http.get('assets/trainings/trainings.json').subscribe(res => {
      const data: Training[] = res.json().data;
      this.state.trainings = data; // <- error
    });
  }

Line 4 throws an error because I mutate the state within the observable subscription. That's fine.

But how do I dispatch another mutator on the store? Within the mutators instance I don't have access to the store. The mutators are a dependency of my store. If I add the store as a dependency of the mutators, I will have a circular dependency which Angular can not resolve.

I can resolve this circular dependency manually but it feels bad to have it or more precise to have to manage it by myself. Maybe Mutators should have a dispatch method and the store the mutators instance belongs to is set by tydux at creation time!?

pburgmer commented 7 years ago

But then the Mutators are statefull and one instance has to belong to one store ...

pburgmer commented 7 years ago

Maybe it's easier to move the orchestration to the store (method on store) and dispatch different mutators from there?

romanroe commented 7 years ago

You need to move the state access in its own mutator, which you can call from your async callback:

loadTrainings() {
    this.http.get('assets/trainings/trainings.json').subscribe(res => {
      const data: Training[] = res.json().data;
      this.assignTrainings(data); // DELEGATE HERE
    });
  }