Christian Benseler
Christian Benseler

Reputation: 8075

Angular2 + ngrx/store: how to change state within a loop?

In an Angular2 app using ngrx/store, I have a method that query some data from an API and dispatch it to the store. It's working ok:

get(id: number) {
  return this.http.get(`http://localhost:3000/contents/${id}.json`).map( response => {
    return response.json();
  })
  .map( (content: Content) => {
    this.store.dispatch({ type: 'GET_CONTENT', payload: content });
    return content;
  });
}

I have also another service that queries the API ans return an array os objects. In this case, I'm doing this:

return this.http.get(`http://localhost:3000/contents/${id}/contents.json`).map( response => {
  return response.json();
})
.map( ( contents: Array<Content>) => {
  contents.map( payload => {
    this.store.dispatch({ type: 'GET_CONTENT', payload });
  });
  return contents;
})

it works, but the state of the store changes multiple times. Is there a better approach? Maybe create another action ('GET_CONTENTS') that everything in the store at the same time? Or can I say, somehow, that the state should only be changed after the 'contents.map' ends?

Upvotes: 0

Views: 802

Answers (1)

JusMalcolm
JusMalcolm

Reputation: 1431

A simple solution would be to edit your reducer to expect an Array<Content> payload. Then, in the case of a single Content just dispatch that value in an array:

this.store.dispatch({ type: 'GET_CONTENT', [content] });

Upvotes: 2

Related Questions