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);
});
}
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.
Top comments (0)