21

I Dispatch a action from one component

this.store.dispatch({type : STORE_TEAMCREST , payload : team.crestURI});

and in the other component i select from the store using

this.store.select(state => state.table.teamCrest).subscribe(data => this.teamCrest = data);

This works fine if my app is going sequentially backward or forward, but once i do a browser refresh the state loses it's value. How to preserve it's value so that it works on browser refresh?

Matthew Cawley
  • 2,688
  • 1
  • 8
  • 19
INFOSYS
  • 1,465
  • 9
  • 23
  • 50

1 Answers1

24

Your store has a subscribe function which will be called any time an action is dispatched, and some part of the state tree may potentially have changed. For a simple solution, you could persist the state to local storage here:

this.store.subscribe(function() {
    localStorage.setItem('state', JSON.stringify(this.store.getState()));
})

Documentation here

Notice that you will need to stringify your state to store it in local storage

To use this state, you will need to pass the local storage state localStorage.getItem('state') (if it exists) as your default state in your reducer. To achieve this, i normally have a helper function check whether an item with key 'state' exists in local storage and calls JSON.parse on the value if it exists.

default reducer case:

default:
        if (retrieveState()) {
            var newState = JSON.parse(retrieveState())          
            return newState
        }
        else {
            return {...whatever your default state is};
        }

Also after a quick look around, there does appear to exist a middleware which should achieve what you are wanting: https://github.com/btroncone/ngrx-store-localstorage

hairmot
  • 2,975
  • 1
  • 13
  • 26
  • how to retive when using store,select the state will it be updated or we need to fetch from local storage ? – INFOSYS Aug 09 '17 at 11:35
  • you continue to use store.select the same way. your store.subscribe function just ensures that the in-memory store is backed up should you kill your in-memory session – hairmot Aug 09 '17 at 11:37
  • 1
    where do i place this subscribe call ? at the roor level or featured level as i have lazy loaded modules 2 – INFOSYS Aug 09 '17 at 11:51
  • i have accepted the answer but i feel as my ngrx component shave lazy loading it is not working properly as when refreshing from lazy loaded components it only fires the parent actions – INFOSYS Aug 09 '17 at 12:01
  • Can somebody explain with ngRx needs LocalStorage? I thought ngRx was supposed to *be* local storage on steroids. – Nick Hodges Mar 23 '20 at 21:33
  • 1
    @NickHodges You should think of it more as an in-memory cache. Persistence would be a plus but alas. luckily this middleware exists – Michael McKenna Nov 19 '20 at 20:24