Ngrx Store Resets after updating the browser. How to make the application save state?

I submit an action from one component

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

and in another component I select from the store using

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

This works great if my application moves sequentially backward or forward, but as soon as I update the browser, the state loses its meaning. How to save this value so that it works when updating the browser?

+9
source share
1 answer

Your store has a subscribe function that will be called at any time when an action is sent, and some part of the state tree can potentially change. For a simple solution, you can save the state in local storage here:

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

Documentation here

Please note that you will need to clip your state in order to save it in local storage

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

default gear case:

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

Also, after a quick look, there is a similar middleware that should achieve what you want: https://github.com/btroncone/ngrx-store-localstorage

+18
source

Source: https://habr.com/ru/post/1270712/


All Articles