0
votes

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?

1
the state should be a pure function for it to work properly and is your function pure?Rahul Singh

1 Answers

2
votes

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] });