1

I am implementing ngrx state management in an Angular 4 app. It was going well until I tried to "hydrate" the app state with the state previously saved in the browser local storage.

I have a question about the Initial State and Ahead of Time Compilation section of ngrx/store documentation. Specifically, what does the following line mean and how would I go about setting ("dynamically injecting at run-time") initialStateFromSomewhere to a state retrieved from browser local storage?

/// Pretend this is dynamically injected at runtime
const initialStateFromSomewhere = { counter: 3 };
ebhh2001
  • 2,034
  • 4
  • 18
  • 27
  • what is the that you are looking for are you trying to set up the intial state the link you provided shows that ? – Rahul Singh Aug 11 '17 at 07:04

1 Answers1

2

While creating your reducer, you provide the initial state for the store.

Assume you have a FeatureState

interface FeatureState {
  counter: number;
}

Now in your reducer you need to create initialState

const initialState: FeatureState = {
  count : 0;
}

This initial State will be supplied to the state in the reducer

export function reducer(state: FeatureState = initialState, action: Action): State {

Now, if you want to dynamically add the initialState, you can retrieve the initialState from the store and pass it in the reducer

Anurag Singh Bisht
  • 2,683
  • 4
  • 20
  • 26
  • Thanks. This is what I am missing. I need to retrieve the `initialState` from localStorage. How do I then get this `initialState` in the `store`, and then get it out of the `store` so that I can pass it in the `reducer`? – ebhh2001 Aug 11 '17 at 10:20
  • So you don't need to get it from the store, you need to just create `initialState` which you can pass as a `default argument` for `reducer` `state` variable. Now the `initialState` you will create will get it's property from the `localStorage` instead of just defaulting them to `0` or `null` – Anurag Singh Bisht Aug 11 '17 at 10:40