Search code examples
angularngrx

sync ngrx store state with database


what the documentation of ngrx illustrate is how to update the state in the store via actions-reducer-effects axis but in case of online trade platform the state of the store(let's say stock of items) the state should be updated by actions not made by the user himself but it should be updated directly from the backend. any references?

my idea is an observable that will dispatch update action on value changes on a subscription (apollo-client) but i have no data to test this approach


Solution

  • Create an effect which listens for data changes and dispatches an appropriate action, which will be picked up by the reducer to update the store.

    Note that while effects are typically triggered via actions, they can also be triggered by an observable (such as valueChanges from an apollo query).

    I am not familiar with apollo but something along these lines should work:

    @Injectable()
    public class DataEffects{
      loadData$ = createEffect(() => 
       this.apollo.watchQuery<Query>({
          query: /* add your query */
        })
        .valueChanges
        .pipe(
          map(result => fooLoadedAction({data: result.data.foo}))
        );
      );
      
      constructor(private apollo: Apollo) { }
    }