1# AppStorageV2: Storing Application-wide UI State 2 3To enhance the capability of the state management framework to store global UI status variables of applications, you are advised to use AppStorageV2. 4 5AppStorageV2 provides the capability of globally sharing state variables within an application. You can bind the same key through **connect** to share data across abilities. 6 7Before reading this topic, you are advised to read [\@ComponentV2](./arkts-new-componentV2.md), [\@ObservedV2 and \@Trace](./arkts-new-observedV2-and-trace.md), and API reference of [AppStorageV2](../reference/apis-arkui/js-apis-StateManagement.md#appstoragev2). 8 9>**NOTE** 10> 11>AppStorageV2 is supported since API version 12. 12> 13 14 15## Overview 16 17AppStorageV2 is a singleton to be created when the application UI is started. Its purpose is to provide central storage for application UI state attributes. And AppStorageV2 retains data during application running. Each attribute is accessed using a unique key, which is a string. 18 19UI components synchronize application state attributes with AppStorageV2. AppStorageV2 can be accessed during implementation of application service logic as well. 20 21AppStorageV2 supports state sharing among multiple UIAbility instances in the [main thread](../application-models/thread-model-stage.md) of an application. 22 23 24## How to Use 25 26### connect: Creating or Obtaining Stored Data 27 28```JavaScript 29static connect<T extends object>( 30 type: TypeConstructorWithArgs<T>, 31 keyOrDefaultCreator?: string | StorageDefaultCreator<T>, 32 defaultCreator?: StorageDefaultCreator<T> 33): T | undefined; 34``` 35 36| connect | Description | 37| ------------ | ----------------------------------------------------- | 38| Parameter | **type**: specified type. If no **key** is specified, the name of the **type** is used as the **key**.<br> **keyOrDefaultCreater**: specified key or default constructor.<br> **defaultCreator**: default constructor. | 39| Return value | After creating or obtaining data, value is returned. Otherwise, **undefined** is returned.| 40 41>**NOTE** 42> 43>1. The third parameter is used when no **key** is specified or the second parameter is invalid. Otherwise, the second parameter is used. 44> 45>2. If the data has been stored in AppStorageV2, you can obtain the stored data without using the default constructor. Otherwise, you must specify the default constructor. If no constructor is specified, the application exception occurs. 46> 47>3. Ensure that the data types match the key. If different types of data are connected to the same key, the application exception occurs. 48> 49>4. You are advised to use meaningful values for keys. The values can contain letters, digits, and underscores (_) and a maximum of 255 characters. Using invalid characters or null characters will result in undefined behavior. 50> 51>5. When match the key with the [\@Observed](arkts-observed-and-objectlink.md) object, specify the key or customize the **name** attribute. 52 53### remove: Deleting the Stored Data of a Specified Key 54 55```JavaScript 56static remove<T>(keyOrType: string | TypeConstructorWithArgs<T>): void; 57``` 58 59| remove | Description | 60| ------------ | ----------------------------------------------------- | 61| Parameter | **keyOrType**: key to be deleted. If the key is of the **Type**, the key to be deleted is the name of the **Type**. | 62| Return value | None.| 63 64>**NOTE** 65> 66>If a key that does not exist in AppStorageV2 is deleted, a warning is reported. 67 68### keys: Returning All Keys Stored in AppStorageV2 69 70```JavaScript 71static keys(): Array<string>; 72``` 73 74| keys | Description | 75| ------------ | ----------------------------------------------------- | 76| Parameter | None. | 77| Return value | All keys stored in AppStorageV2.| 78 79 80## Constraints 81 821. This singleton must be used together with the UI thread only. Other threads, for example, @Sendable decorator is not supported. 83 842. Types such as collections.Set and collections.Map are not supported. 85 863. Non-buildin types, such as native PixelMap, NativePointer, and ArrayList types, are not supported. 87 88## Use Scenarios 89 90### Storing Data Between Two Pages 91 92Page 1 93```ts 94import { AppStorageV2 } from '@kit.ArkUI'; 95import { Sample } from '../Sample'; 96 97@Entry 98@ComponentV2 99struct Page1 { 100 // Create a KV pair whose key is Sample in AppStorageV2 (if the key exists, the data in AppStorageV2 is returned) and associate it with prop. 101 @Local prop: Sample = AppStorageV2.connect(Sample, () => new Sample())!; 102 pageStack: NavPathStack = new NavPathStack(); 103 104 build() { 105 Navigation(this.pageStack) { 106 Column() { 107 Button('Go to page2') 108 .onClick(() => { 109 this.pageStack.pushPathByName('Page2', null); 110 }) 111 112 Button('Page1 connect the key Sample') 113 .onClick(() => { 114 // Create a KV pair whose key is Sample in AppStorageV2 (if the key exists, the data in AppStorageV2 is returned) and associate it with prop. 115 this.prop = AppStorageV2.connect(Sample, 'Sample', () => new Sample())!; 116 }) 117 118 Button('Page1 remove the key Sample') 119 .onClick(() => { 120 // After being deleted from AppStorageV2, prop will no longer be associated with the value whose key is Sample. 121 AppStorageV2.remove(Sample); 122 }) 123 124 Text(`Page1 add 1 to prop.p1: ${this.prop.p1}`) 125 .fontSize(30) 126 .onClick(() => { 127 this.prop.p1++; 128 }) 129 130 Text(`Page1 add 1 to prop.p2: ${this.prop.p2}`) 131 .fontSize(30) 132 .onClick(() => { 133 // The page is not re-rendered, but the value of p2 is changed. 134 this.prop.p2++; 135 }) 136 137 // Obtain all keys in the current AppStorageV2. 138 Text(`all keys in AppStorage: ${AppStorageV2.keys()}`) 139 .fontSize(30) 140 } 141 } 142 } 143} 144``` 145 146Page 2 147```ts 148import { AppStorageV2 } from '@kit.ArkUI'; 149import { Sample } from '../Sample'; 150 151@Builder 152export function Page2Builder() { 153 Page2() 154} 155 156@ComponentV2 157struct Page2 { 158 // Create a KV pair whose key is Sample in AppStorageV2 (if the key exists, the data in AppStorageV2 is returned) and associate it with prop. 159 @Local prop: Sample = AppStorageV2.connect(Sample, () => new Sample())!; 160 pathStack: NavPathStack = new NavPathStack(); 161 162 build() { 163 NavDestination() { 164 Column() { 165 Button('Page2 connect the key Sample1') 166 .onClick(() => { 167 // Create a KV pair whose key is Sample1 in AppStorageV2 (if the key exists, the data in AppStorageV2 is returned) and associate it with prop. 168 this.prop = AppStorageV2.connect(Sample, 'Sample1', () => new Sample())!; 169 }) 170 171 Text(`Page2 add 1 to prop.p1: ${this.prop.p1}`) 172 .fontSize(30) 173 .onClick(() => { 174 this.prop.p1++; 175 }) 176 177 Text(`Page2 add 1 to prop.p2: ${this.prop.p2}`) 178 .fontSize(30) 179 .onClick(() => { 180 // The page is not re-rendered, but the value of p2 is changed, which is performed after re-initialization. 181 this.prop.p2++; 182 }) 183 184 // Obtain all keys in the current AppStorageV2. 185 Text(`all keys in AppStorage: ${AppStorageV2.keys()}`) 186 .fontSize(30) 187 } 188 } 189 .onReady((context: NavDestinationContext) => { 190 this.pathStack = context.pathStack; 191 }) 192 } 193} 194``` 195When using **Navigation**, you need to add the **route_map.json** file to the **src/main/resources/base/profile** directory, replace the value of **pageSourceFile** with the path of **Page2**, and add **"routerMap": "$profile: route_map"** to the **module.json5** file. 196```json 197{ 198 "routerMap": [ 199 { 200 "name": "Page2", 201 "pageSourceFile": "src/main/ets/pages/PersistenceV2-2.ets", 202 "buildFunction": "Page2Builder", 203 "data": { 204 "description" : "PersistenceV2 example" 205 } 206 } 207 ] 208} 209``` 210 211Data page 212```ts 213// Data center 214@ObservedV2 215export class Sample { 216 @Trace p1: number = 0; 217 p2: number = 10; 218} 219``` 220