Search code examples
jsonangularionic-frameworkngrx

How to achieve state persistence even after a reload in Ngrx


I have a shopping cart which I am maintaining with Ngrx and for maintaining the persistence of the state after a page refresh I have two options:

  1. Stringify the state and store it in local storage and get it back after the reload.
  2. Stringify the state and store it inside a text file and then get the string out of the file and use JSON.parse to convert the string back to a JSON object.

I am storing some price related data so didn't want to store in local storage.

What should I use? Or is there any better way to do this?


Solution

  • You can use the ngrx-store-localstorage package as https://stackoverflow.com/a/58362198/10112124 mentioned, or write your custom meta-reducer or as you mentioned use effects to do this. For the latter, Tomas Trajan has an example in his angular-ngrx-material-starter project.

    All the above options are find, but I wanted to give an answer on what to store

    I am storing some price related data so didn't want to store in local storage.

    If you have sensitive information, you could store it in the sessions storage - when the session is ended, the storage will be cleaned up.

    You shouldn't have to store sensitive information, why don't you store important information like the article id and the quantity? This way you can rehydrate the store with this information, and build up your shopping cart with this information plus the products of the catalog you would load in a normal way.