jwjbadger
jwjbadger

Reputation: 57

NgRx Perform Action (asynchronously) After Dispatching Action

Note that this question is a clarification question

What I Need To Do

I am trying to dispatch an action to NgRx that will add a task to a list of tasks. After this, I need to make a put request to an API to store the new changes. The problem, is that I need to do this asynchronously, but this.store.dispatch(...) returns void. I have a feeling this might be where effects come in handy, but my questions are: is there a better way to do it and is effects the 'right' way. The code below just describes what I am doing currently. The problem with how it works is that the user should click a button, which calls this function with the appropriate parameters, but then the put request happens before this.store.dispatch(...) finishes, so it only records previously recorded changes, and not what it should be. The other way I could think of doing this is to reconstruct this.project within the projectService.putProject(...) call with the new changes. Which way is best? I realize this is probably a pretty ignorant question, so sorry.

The Code

createNew(title: string, description: string) {
    this.store.dispatch(
      AddTask({
        payload: {
          title: title,
          description: description,
          projectIndex: this.index,
        },
      })
    );
    this.projectService.putProject(this.project).subscribe();
  }

Upvotes: 0

Views: 370

Answers (1)

timdeschryver
timdeschryver

Reputation: 15505

Yes, effects are the best place to put this logic imho. You could also listen for actions in the component itself (by using ActionsSubject), but then you're basically writing your own effect, and you have to deal with the subscription yourself. See https://github.com/typebytes/angular-checklist/blob/3a6cf03d06b3e872d92069856c87678bcd6b21c7/src/app/checklist/search/search.service.ts#L26-L32 for an example.

Upvotes: 1

Related Questions