T Jagadish Gupta
T Jagadish Gupta

Reputation: 19

When page reloads ngrx store data is refreshed to initial state

How to store ngrx data persistently in angular 7 Consider the below scenario

1.When we login we will store user information
2.When user updates his profile then we dispatch a change and data will be updated in all components
3.here the problem is when page refresh happens the ngrx store data is gone how to solve this

My problem is to make one resource and connect this resource to all desired components and when some change happens to resources (data) how to reflect the change to all associated components Please help me how to achieve this

Upvotes: 1

Views: 5648

Answers (2)

Xesenix
Xesenix

Reputation: 2548

Use ngrx-store-localstorage for example like this:

import { StoreModule } from '@ngrx/store';
import { localStorageSync } from 'ngrx-store-localstorage';

export function localStorageSyncReducer(rootReducer: any) {
    return localStorageSync({ keys: ['what', 'keys', 'do', 'you', 'want', 'to', 'store'], rehydrate: true })(rootReducer);
}

@NgModule({
  imports: [
    StoreModule.forRoot(reducer, {
      metaReducers: [..., localStorageSyncReducer],
    }),
  ],
  ...

Where keys represent keys used by reducer: see documentation

Upvotes: 2

schoolcoder
schoolcoder

Reputation: 1654

ngrx store is meant for state management. In the end, we are using a single page application. On page refresh, every source including ngrx store will be refreshed.

In your case, for the logged in user, you would have the cookie.

To retain the user information, you need to request your back end only one time when the app is fully loaded on the browser.

For this, in the app.module.ts use APP_INITIALIZER provider something like below,

providers: [
  ...
   SessionProvider,
   { provide: APP_INITIALIZER, useFactory: sessionProviderFactory, deps: [SessionProvider], multi: true },
  ...
]

SessionProviderFactory.ts

export function sessionProviderFactory(provider: SessionProvider) {
 return () => provider.load();
}

SessionProvider.ts

@Injectable()
export class SessionProvider {
 constructor(private httpClient: HttpClient, private store: Store<AppState>) { }

  load(): Promise<boolean> {
  return new Promise<boolean>((resolve, reject) => {
  this.httpClient.get('/rest/v1/user').subscribe(
    (res: UserModel) => {
      // in this step, store the value in the ngRx store
      this.store.dispatch(new Login(res));
      resolve(true);
    },
    (error) => {
      //error handling..
    }
  );
  });
 }
}

Upvotes: 0

Related Questions