Ced
Ced

Reputation: 17377

ngrx, How to have a starting state from an api?

I have my reducer with a starting state of an empty array:

folderReducer(state:Array<Folder> = [], action: Action)

I'd like to populate the starting state, so when I do

store.subscribe(s => ..)

The first item I get comes from the database. I assume the way of doing this is with ngrx/effects, but I'm not sure how.

Upvotes: 4

Views: 7217

Answers (2)

user3336882
user3336882

Reputation: 3333

A dynamic initial state is now supported, see: https://github.com/ngrx/platform/blob/master/docs/store/api.md#initial-state-and-ahead-of-time-aot-compilation

Also see: https://github.com/ngrx/platform/issues/51

I would only do this if the database is local, otherwise the request will hold up loading of the application.

Upvotes: 1

Olaf Horstmann
Olaf Horstmann

Reputation: 16892

Your store always has the initial state, that you define in the reducer-function. The initial states main purpose is to ensure that the application is able to start up and not run into any null-pointer-exceptions. And also it sets up your application to start making the first api-calls ect. - so you can think of it as a technical initial state.

If you want to fill your store with api-data on the startup, you would do that on the same way that you add/modify data during any other action - just that the action of "initially loading data" is not triggered by some user-interaction but through:

  • either when your root-component loads
  • or as part of a service in the constructor

In case you want to prevent specific components from showing anything until your API-call is done, you would have to adjust the display-components to display or hide data based on your state (e.g. by implementing a flag in your satet initialDataLoaded).

Upvotes: 12

Related Questions