Blog>
Snippets

Persisting State with Akita PersistState Plugin

Demonstrate the usage of Akita's PersistState plugin to automatically persist and rehydrate store state across page reloads in an Angular app.
import { persistState } from '@datorama/akita';

// Call this function in the main.ts or app.module.ts to initialize persist state
export function initAkitaPersistState() {
  persistState({
    include: ['session'], // Replace 'session' with the name of the store you want to persist
    // additional options can be added here
  });

  // When hard-reloading the app (Ctrl+F5), clear the persisted state.
  // Remove this if you want the state to persist even after a hard reload.
  window.onbeforeunload = () => {
    if (window.performance) {
      if (performance.navigation.type === 1) {
        localStorage.clear();
      }
    }
  };
}
This JavaScript snippet is used to configure the Akita PersistState plugin to automatically save and rehydrate a specific store (in this case named 'session') in an Angular application. The snippet also includes an example of how to clear the persist state on hard reload, which is optional.
import { Component } from '@angular/core';
import { SessionStore } from './session.store';

@Component({
  selector: 'app-root',
  template: `<div>
                <h1>Session State</h1>
                <button (click)="updateSession()">Update Session</button>
              </div>`,
  styles: [`button { margin: 20px; }`]
})
export class AppComponent {
  constructor(private sessionStore: SessionStore) {}

  updateSession() {
    // Update the session state
    this.sessionStore.update(state => ({
      ...state,
      // your state updates here
    }));
  }
}
This Angular component uses Akita's SessionStore to demonstrate how to update the state. The persistState plugin would automatically save these state changes, and upon page reload, the state would be rehydrated. A button is provided in the component's template to trigger the state update.
// In your Angular AppModule, you would initialize Akita PersistState
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { initAkitaPersistState } from './persist-state-init';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {
  constructor() {
    initAkitaPersistState(); // Initialize AkitaPersistState
  }
}
This snippet shows where to initialize the persistState function in an Angular module, most likely the root module (`AppModule`). By calling `initAkitaPersistState()` in the constructor, the persist state is set up before the application is fully bootstrapped.