Search code examples
angularlocal-storagengrxstate-management

How to save to local storage using Ngrx?


I am trying to save a simple menu state whether it is 'open' or 'close' to the browser localStorage. I know I can do it by using localStorage.setItem. But, my project is using NGRX. Is there a better way to deal this using NGRX? By default, the menu is open. If I close it and close the browser and return back, it should be closed.

Is there a way to do it using NGRX or localStorage is the better solution? I am just learning NGRX. Any help is appreciated.


Solution

  • You can make a function that you set in your initial state that could pull data from local storage

    StoreModule.forRoot(
        { someReducer: reducer },
        { initialState: getInitialAppState }
      ),
    

    then in the function you could do something like this

    export function getInitialAppState() {
        const previousSettings  = localStorage.getItem("settings")
        if (previousSettings  != null) {
             return JSON.parse(previousSettings);
        }
        return {};
    }
    

    So if you stored some settings at one point in a previous setting it will set that as an inistal state. to store these settings you can have a selector in your app.component or somewhere more fitting listing to settings and just JSON.stringify that state you want to store.