Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The right way of using ngrx/store to update store

I'm learning ngrx/store and I have a component that call to a service to get some data from the server, as I refactor it to use ngrx/store, I don't know where to update the store.

As I understand I have 2 options:

  1. Call the service from the component, get the data, and use dispatch to update to store.
  2. Call the service from the component, and the service will update the store state using dispatch. The component can subscribe to that part of the state (using select) and when the service will get the data and update the state, the component will get the update through the store subscription.

Which is the right ("Best Practice") way to go? (Maybe there is another why I should do this?)

like image 580
Nirgn Avatar asked Oct 25 '16 20:10

Nirgn


People also ask

What is a good use case for NgRx store?

NgRx is a global state management library that helps decouple the Domain and Business layers from the Rendering layer. It's fully reactive. All changes can be listened to using simple Observables, which makes complex business scenarios easier to handle.

What is NgRx store management?

NgRx Store provides reactive state management for Angular apps inspired by Redux. Unify the events in your application and derive state using RxJS.


1 Answers

You should do it using @ngrx/effects.

  1. Component dispatches an action: LOGIN
  2. Effect catches the action.
  3. Effect triggers the service to get the data.
  4. Effect returns a new action with the data.
  5. Reducer gets the new action with data as payload and builds the state.

This is the best practice.

See my repo for examples of using effects.

Memroy Game (with effects)

like image 77
Shlomi Levi Avatar answered Nov 15 '22 23:11

Shlomi Levi