DEV Community

HarmonyOS
HarmonyOS

Posted on

[Smart Watch] [API 6] Using 'PersistentStorage' for data persistence does not work

Read the original article:[Smart Watch] [API 6] Using 'PersistentStorage' for data persistence does not work

Question

Why does data stored with AppStorage.setOrCreate and PersistentStorage.persistProp not persist after the app is killed and restarted?

Short Answer

Because PersistentStorage.persistProp must be initialized in the entryAbility. If it is only called in a page, the data will not be properly saved across app restarts.

// This function is called when the window stage is created
onWindowsStageCrerate(windowStage: window.WindowStage): void {
  // Load the content (i.e., a page) into the window stage
  windowStage.loadContent('pages/Index', (err) => {
    // If an error occurs while loading the content, exit early
    if (err.code) {
      return;
    }

    // If the page loads successfully, persist a property named 'aProp' with the value 47
    PersistentStorage.persistProp('aProp', 47);
  });
}
Enter fullscreen mode Exit fullscreen mode

Applicable Scenarios

Use this solution when you want to persist application data (such as user preferences or state variables) across app restarts in HarmonyOS. Ensure that PersistentStorage.persistProp is initialized in entryAbility to guarantee persistence.

Written by Emine Inan

Top comments (0)