1

I currently working on a smaller project where I start to do some user management. There are plenty of options, but I wanted to follow good code practices.

Usually is it better to store user profile information in the store (Ngrx) or should I use the localStorage for that.

interface Profile {
    nickname: String;
    profileImage: String;
    slogan: String;
}

When should I use the localStorage instead of the ngrx store?

Thank you in advance. Hope this question is not too general.

Ling Vu
  • 4,740
  • 5
  • 24
  • 45
  • It's based on your need, refer this https://medium.com/frontend-fun/angular-ngrx-a-clean-and-clear-introduction-4ed61c89c1fc – Prawin soni Oct 23 '19 at 13:28

3 Answers3

3

The question isn't which to choose, they go hand-in-hand.

For example you can have your state inside ngrx store and the exact same state can be persisted to local storage. That way, you can re-hydrate your store state with the state from local storage.

User information should live in memory, thus in the store state.

  • It's probably shared state across multiple parts of your application
  • It's safer to store in memory
timdeschryver
  • 14,415
  • 1
  • 19
  • 32
  • That's what I wanted to know. Thanks for sharing. – Ling Vu Oct 23 '19 at 13:36
  • @LingVu this answer is very helpful, thanks. A follow up question: if some components need that data, it's better to load from the store (or service) instead of the localStorage, right? Otherwise, the store (or the service in my case) is useless – chris May 06 '20 at 19:08
2

The Ngrx store will be erased once you refresh the page while the localStorage persists on the browser even after refresh. Although the localStorage is saved by domain and by browser so it will only be available for the current browser and it will only be available for that specific domain.

You should use the localStorage if you want your data to persing after the user refreshes the page.

There's a great thread if you want to persist your information on the localStorage. Check gere: Ngrx Store Resets after browser refresh. How to make the application preserve the state?

Also, you can have a look at a library called ngrx-store-localstorage, this module is automatically synchronizing a ngrx-store with the localstorage if you are using the rehydrate option.

Diogo Peres
  • 1,302
  • 1
  • 11
  • 20
0

You can use Cookie as well. npm (modules) for Cookie is also available. Please search npm cookie.