Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ngrx

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.

like image 230
Ced Avatar asked Oct 27 '25 10:10

Ced


1 Answers

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).

like image 58
olsn Avatar answered Oct 29 '25 08:10

olsn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!