4
votes

This is my first question so please be gentle.

I'm using ngrx/store in my angular app and I wanted to set the initial state of my reducer functions using data from firebase. However, without a constructor function in my reducer.ts file, I'm unsure of how to perform an async action.

I'm aware of ngrx effects and how to use them, but I don't see a way to set my reducers initial state using effects.

Hopefully, there's a simple example of this someone wouldn't mind posting to help a fledgling developer like myself.

3
Plenty of tutorial, just google it. If you want to take a look into a repo with ngrx I've made a medium one that might help you understand all of that: github.com/maxime1992/pizza-syncmaxime1992

3 Answers

1
votes

The point of initial state is that it is the state that is available in the very beginning, meaning that you would have to set it right away.

If you are getting the state asynchronously then you can use the same method you would use to update the state normally store.dispatch(...) when your call to firebase comes back with data.

More information in this answer here: ngrx, How to have a starting state from an api?

1
votes

The difficulty you will face when trying to provide an initial state from an asynchronous source is that ngrx reducers and the store initialisation are synchronous.

But you can still achieve it by following these steps:

  • load your asynchronous initial state with a promise that you provide to the angular APP_INITIALIZER (it will delay app init until all promise are resolved)
  • this state for later synchronous access by ngrx
  • trigger your own init Action when the angular ApplicationInitStatus.donePromise is resolved
  • listen for this action (which will be the first of your own, some ngrx store/effects initialisation actions will pass before) in your reducer to use the previously stored initial state.

This is a bit too much code/too broad a topic for an answer, but I wrote about this in more details and with code samples in my post "use indexedDb with ngrx for fast application bootstrap"

You can also follow this (somewhat old) issue where someone mentioned that async initialization would be nice if ngrx would support persistent state.

0
votes

Maybe to late my answer but it can help others.

The important point here is the init function for each effect. Which is really good explained from dee zg in following issue

There is an init action in effects which fires when effects get ran. There you can dispatch your action, get data and fill initial state. Check Init Action section here: https://github.com/ngrx/platform/blob/master/MIGRATION.md