• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.arkui.StateManagement (State Management)
2
3The state management module provides data storage, persistent data management, UIAbility data storage, and environment state and tools required by applications.
4
5>**NOTE**
6>
7>The initial APIs of this module are supported since API version 12.
8
9
10The meanings of T and S in this topic are as follows:
11
12
13| Type  | Description                                    |
14| ---- | -------------------------------------- |
15| T    | Class, number, boolean, string, and arras of these types.|
16| S    | number, boolean, string.                |
17
18
19## AppStorageV2
20
21For details about how to use AppStorageV2, see [AppStorageV2: Storing Application-wide UI State](../../quick-start/arkts-new-appstoragev2.md).
22
23### Modules to Import
24
25```ts
26import { AppStorageV2 } from '@kit.ArkUI';
27```
28
29### connect<sup>12+</sup>
30
31static connect\<T extends object\>( <br>
32      type: TypeConstructorWithArgs\<T\>, <br>
33      keyOrDefaultCreator?: string | StorageDefaultCreator\<T\>, <br>
34      defaultCreator?: StorageDefaultCreator\<T\> <br>
35): T | undefined;
36
37Stores key-value pair data in the application memory. If the given key already exists in [AppStorageV2](../../quick-start/arkts-new-appstoragev2.md), it returns the corresponding value; otherwise, it constructs a default value using the constructor for obtaining the default value and returns it.
38
39**Atomic service API**: This API can be used in atomic services since API version 12.
40
41**System capability**: SystemCapability.ArkUI.ArkUI.Full
42
43**Parameters**
44
45| Name  | Type  | Mandatory| Description              |
46| -------- | ------ | ---- | ---------------------- |
47| type | TypeConstructorWithArgs\<T\> | Yes  | Type. If no key is specified, the name of the type is used as the key.|
48| keyOrDefaultCreater | string \| StorageDefaultCreator\<T\> | No  | Key, or the constructor for obtaining the default value.|
49| defaultCreator | StorageDefaultCreator\<T\> | No  | Constructor for obtaining the default value.|
50
51>**NOTE**
52>
53>1. If no key is specified, the second parameter is used as the default constructor; otherwise, the third parameter is used as the default constructor.
54>
55>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, an application exception will occur.
56>
57>3. Ensure type compatibility. Connecting data of different types with the same key will cause an application exception.
58>
59>4. You are advised to use meaningful values for the key, with a length not exceeding 255 characters. The behavior of using illegal characters or empty characters is undefined.
60
61**Return value**
62
63| Type                                  | Description                                                        |
64| -------------------------------------- | ------------------------------------------------------------ |
65| T | Returns data if the creation or data acquisition from AppStorageV2 is successful; returns **undefined** otherwise.|
66
67**Example**
68
69```ts
70import { AppStorageV2 } from '@kit.ArkUI';
71
72@ObservedV2
73class SampleClass {
74  @Trace p: number = 0;
75}
76
77// Store the key-value pair with the key SampleClass and the value as a new instance of SampleClass() in memory, and assign it to variable as1.
78const as1: SampleClass | undefined = AppStorageV2.connect(SampleClass, () => new SampleClass());
79
80// Store the key-value pair with the key key_as2 and the value as a new instance of SampleClass() in memory, and assign it to variable as2.
81const as2: SampleClass = AppStorageV2.connect(SampleClass, 'key_as2', () => new SampleClass())!;
82
83// As the key SampleClass already exists in AppStorageV2, the value associated with the key is returned to variable as3.
84const as3: SampleClass = AppStorageV2.connect(SampleClass) as SampleClass;
85```
86
87### remove<sup>12+</sup>
88
89static remove\<T\>(keyOrType: string | TypeConstructorWithArgs\<T\>): void;
90
91Removes the specified key-value pair from [AppStorageV2](../../quick-start/arkts-new-appstoragev2.md). If the specified key does not exist in AppStorageV2, the removal will fail.
92
93**Atomic service API**: This API can be used in atomic services since API version 12.
94
95**System capability**: SystemCapability.ArkUI.ArkUI.Full
96
97**Parameters**
98
99| Name  | Type  | Mandatory| Description              |
100| -------- | ------ | ---- | ---------------------- |
101| keyOrType | string \| TypeConstructorWithArgs\<T\> | Yes  | Key to be removed. If a type is specified, the key to be deleted is the name of that type.|
102
103>**NOTE**
104>
105>Attempting to remove a key that does not exist in AppStorageV2 will result in a warning.
106
107**Return value**
108
109None.
110
111**Example**
112
113```ts
114// Assuming that there is a key named key_as2 in AppStorageV2, the following will remove the corresponding key-value pair from AppStorageV2.
115AppStorageV2.remove('key_as2');
116
117// Assuming that there is a key named SampleClass in AppStorageV2, the following will remove the corresponding key-value pair from AppStorageV2.
118AppStorageV2.remove(SampleClass);
119
120// Assuming there is no key named key_as1 in AppStorageV2, the following will result in a warning.
121AppStorageV2.remove('key_as1');
122```
123
124### keys<sup>12+</sup>
125
126static keys(): Array\<string\>;
127
128Obtains all keys in [AppStorageV2](../../quick-start/arkts-new-appstoragev2.md).
129
130**Atomic service API**: This API can be used in atomic services since API version 12.
131
132**System capability**: SystemCapability.ArkUI.ArkUI.Full
133
134**Parameters**
135
136None.
137
138**Return value**
139
140| Type                                  | Description                                                        |
141| -------------------------------------- | ------------------------------------------------------------ |
142| Array\<string\> | All keys stored in AppStorageV2.|
143
144>**NOTE**
145>
146>The order of the keys in the Array is not sequential and does not correspond to the order in which the keys were inserted into AppStorageV2.
147
148**Example**
149
150```ts
151// Assuming there are two keys (key_as1 and key_as2) in AppStorageV2, the following will return an array containing these keys and assign it to keys.
152const keys: Array<string> = AppStorageV2.keys();
153```
154
155
156
157## PersistenceV2
158
159For details about how to use PersistenceV2, see [PersistenceV2: Persisting Application State](../../quick-start/arkts-new-persistencev2.md).
160
161### Modules to Import
162
163```ts
164import { PersistenceV2 } from '@kit.ArkUI';
165```
166
167### connect<sup>12+</sup>
168
169static connect\<T extends object\>( <br>
170      type: TypeConstructorWithArgs\<T\>, <br>
171      keyOrDefaultCreator?: string | StorageDefaultCreator\<T\>, <br>
172      defaultCreator?: StorageDefaultCreator\<T\> <br>
173): T | undefined;
174
175Stores the key-value pair data on the application disk (for persistence). If the given key already exists in [PersistenceV2](../../quick-start/arkts-new-persistencev2.md), it returns the corresponding value; otherwise, it constructs a default value using the constructor for obtaining the default value and returns it. If what is connected is an [\@ObservedV2](../../quick-start/arkts-new-observedV2-and-trace.md) object, changes to the object's [\@Trace](../../quick-start/arkts-new-observedV2-and-trace.md) decorated property will trigger automatic persistence of the entire associated object; changes to non-@Trace-decorated properties will not. If necessary, you can manually persist data by calling the **PersistenceV2.save** API.
176
177**Atomic service API**: This API can be used in atomic services since API version 12.
178
179**System capability**: SystemCapability.ArkUI.ArkUI.Full
180
181**Parameters**
182
183| Name  | Type  | Mandatory| Description              |
184| -------- | ------ | ---- | ---------------------- |
185| type | TypeConstructorWithArgs\<T\> | Yes  | Type. If no key is specified, the name of the type is used as the key.|
186| keyOrDefaultCreater | string \| StorageDefaultCreator\<T\> | No  | Key, or the constructor for obtaining the default value.|
187| defaultCreator | StorageDefaultCreator\<T\> | No  | Constructor for obtaining the default value.|
188
189>**NOTE**
190>
191>1. If no key is specified, the second parameter is used as the default constructor; if the second parameter is invalid, the third parameter is used as the default constructor
192>
193>2. If the data has been stored in PersistenceV2, you can obtain the stored data without using the default constructor. Otherwise, you must specify the default constructor. If no constructor is specified, an application exception occurs.
194>
195>3. Ensure type compatibility. Connecting data of different types with the same key will cause an application exception.
196>
197>4. You are advised to use meaningful values for keys. The values can contain letters, digits, and underscores (_) and a maximum of 255 characters. If use invalid characters or null characters, undefined behavior will occur.
198
199**Return value**
200
201| Type                                  | Description                                                        |
202| -------------------------------------- | ------------------------------------------------------------ |
203| T | Returns data if the creation or data acquisition from AppStorageV2 is successful; returns **undefined** otherwise.|
204
205**Example**
206
207```ts
208import { PersistenceV2, Type } from '@kit.ArkUI';
209
210@ObservedV2
211class SampleClass {
212  @Trace p1: number = 0;
213  p2: number = 1;
214}
215
216@ObservedV2
217class FatherSampleClass {
218  @Trace f: SampleClass = new SampleClass();
219}
220
221// Persist the key-value pair with the key SampleClass and the value as an instance of SampleClass(), and assign it to variable as1.
222const as1: FatherSampleClass | undefined = PersistenceV2.connect(FatherSampleClass, () => new FatherSampleClass());
223
224// Persist the key-value pair with the key key_as2 and the value as an instance of SampleClass(), and assign it to variable as2.
225const as2: FatherSampleClass = PersistenceV2.connect(FatherSampleClass, 'key_as2', () => new FatherSampleClass())!;
226
227// As the key SampleClass already exists in PersistenceV2, the value associated with the key is returned to variable as3.
228const as3: FatherSampleClass = PersistenceV2.connect(FatherSampleClass) as FatherSampleClass;
229
230@Entry
231@Component
232struct SampleComp {
233  v: FatherSampleClass = as2;
234
235  build() {
236    Column() {
237      Text(`${this.v.f.p1}`)
238        .onClick(() => {
239          // Automatic persistence
240          this.v.f.p1++;
241        })
242      Text(`${this.v.f.p2}`)
243        .onClick(() => {
244          // Automatic persistence is not available. You need to call the PersistenceV2.save API for manual persistence.
245          this.v.f.p2++;
246        })
247    }
248  }
249}
250```
251
252### remove<sup>12+</sup>
253
254static remove\<T\>(keyOrType: string | TypeConstructorWithArgs\<T\>): void;
255
256Removes the specified key-value pair from [PersistenceV2](../../quick-start/arkts-new-persistencev2.md). If the specified key does not exist in PersistenceV2, the removal will fail.
257
258**Atomic service API**: This API can be used in atomic services since API version 12.
259
260**System capability**: SystemCapability.ArkUI.ArkUI.Full
261
262**Parameters**
263
264| Name  | Type  | Mandatory| Description              |
265| -------- | ------ | ---- | ---------------------- |
266| keyOrType | string \| TypeConstructorWithArgs\<T\> | Yes  | Key to be removed. If a type is specified, the key to be deleted is the name of that type.|
267
268>**NOTE**
269>
270>Attempting to remove a key that does not exist in PersistenceV2 will result in a warning.
271
272**Return value**
273
274None.
275
276**Example**
277
278```ts
279// Assuming that there is a key named key_as2 in PersistenceV2, the following will remove the corresponding key-value pair from PersistenceV2.
280PersistenceV2.remove('key_as2');
281
282// Assuming that there is a key named SampleClass in PersistenceV2, the following will remove the corresponding key-value pair from PersistenceV2.
283PersistenceV2.remove(SampleClass);
284
285// Assuming there is no key named key_as1 in PersistenceV2, the following will result in a warning.
286PersistenceV2.remove('key_as1');
287```
288
289### keys<sup>12+</sup>
290
291static keys(): Array\<string\>;
292
293Obtains all keys in [PersistenceV2](../../quick-start/arkts-new-persistencev2.md).
294
295**Atomic service API**: This API can be used in atomic services since API version 12.
296
297**System capability**: SystemCapability.ArkUI.ArkUI.Full
298
299**Parameters**
300
301None.
302
303**Return value**
304
305| Type                                  | Description                                                        |
306| -------------------------------------- | ------------------------------------------------------------ |
307| Array\<string\> | All keys in PersistenceV2.|
308
309>**NOTE**
310>
311>The order of the keys in the Array is not sequential and does not correspond to the order in which the keys were inserted into PersistenceV2.
312
313**Example**
314
315```ts
316// Assuming there are two keys (key_as1 and key_as2) in PersistenceV2, the following will return an array containing these keys and assign it to keys.
317const keys: Array<string> = PersistenceV2.keys();
318```
319
320### save<sup>12+</sup>
321
322static save\<T\>(keyOrType: string | TypeConstructorWithArgs\<T\>): void;
323
324Persists the specified key-value pair data once.
325
326**Atomic service API**: This API can be used in atomic services since API version 12.
327
328**System capability**: SystemCapability.ArkUI.ArkUI.Full
329
330**Parameters**
331
332| Name  | Type  | Mandatory| Description              |
333| -------- | ------ | ---- | ---------------------- |
334| keyOrType | string \| TypeConstructorWithArgs\<T\> | Yes  | Key to be persisted. If a type is specified, the key for persistence is the name of the type.|
335
336>**NOTE**
337>
338>Since changes to non-[\@Trace](../../quick-start/arkts-new-observedV2-and-trace.md) decorated data do not trigger automatic persistence by [PersistenceV2](../../quick-start/arkts-new-persistencev2.md), this API can be called if necessary to persist the data for the corresponding key.
339>
340>It is useless to manually persist the keys that are not in the **connect** state in the memory.
341
342**Return value**
343
344None.
345
346**Example**
347
348```ts
349// Assuming there is a key named key_as2 in PersistenceV2, the following will persist the data for this key-value pair.
350PersistenceV2.save('key_as2');
351
352// Assuming there is a key named SampleClass in PersistenceV2, the following will persist the data for this key-value pair.
353PersistenceV2.remove(SampleClass);
354
355// Assuming there is no key named key_as1 in PersistenceV2, this operation is meaningless.
356PersistenceV2.remove('key_as1');
357```
358
359## UIUtils
360
361Provides APIs for handling data transformations related to state management.
362
363### Modules to Import
364
365```ts
366import { UIUtils } from '@kit.ArkUI';
367```
368
369### getTarget<sup>12+</sup>
370
371static getTarget\<T extends object\>(source: T): T;
372
373Obtains the original object from a proxy object wrapped by the state management framework. For details, see [getTarget API: Obtaining Original Objects](../../quick-start/arkts-new-getTarget.md).
374
375**Atomic service API**: This API can be used in atomic services since API version 12.
376
377**System capability**: SystemCapability.ArkUI.ArkUI.Full
378
379**Parameters**
380
381| Name| Type| Mandatory| Description    |
382| ------ | ---- | ---- | ------------ |
383| source | T    | Yes  | Source object.|
384
385**Return value**
386
387| Type| Description                                            |
388| ---- | ------------------------------------------------ |
389| T    | Original object of the source after the proxy added by the state management framework is removed.|
390
391**Example**
392
393```ts
394import { UIUtils } from '@kit.ArkUI';
395class NonObservedClass {
396  name: string = "Tom";
397}
398let nonObservedClass: NonObservedClass = new NonObservedClass();
399@Entry
400@Component
401struct Index {
402  @State someClass: NonObservedClass = nonObservedClass;
403  build() {
404    Column() {
405      Text(`this.someClass === nonObservedClass: ${this.someClass === nonObservedClass}`) // false
406      Text(`UIUtils.getTarget(this.someClass) === nonObservedClass: ${UIUtils.getTarget(this.someClass) ===
407        nonObservedClass}`) // true
408    }
409  }
410}
411```
412### makeObserved<sup>12+</sup>
413
414static makeObserved\<T extends object\>(source: T): T;
415
416Converts ordinary unobservable data into observable data. For details, see [makeObserved API: Changing Unobservable Data to Observable Data](../../quick-start/arkts-new-makeObserved.md).
417
418**Atomic service API**: This API can be used in atomic services since API version 12.
419
420**System capability**: SystemCapability.ArkUI.ArkUI.Full
421
422**Parameters**
423
424| Name| Type| Mandatory| Description    |
425| ------ | ---- | ---- | ------------ |
426| source | T    | Yes  | Source object. It supports classes not decorated by @Observed or @ObserveV2, objects returned by **JSON.parse**, and classes decorated by @Sendable.<br>Array, Map, Set, and Date types are supported.<br>**collection.Array**, **collection.Set**, and **collection.Map** are supported.<br>For details, see [makeObserved API: Changing Unobservable Data to Observable Data](../../quick-start/arkts-new-makeObserved.md).|
427
428**Return value**
429
430| Type| Description                                            |
431| ---- | ------------------------------------------------ |
432| T    | Observable data.|
433
434**Example**
435
436```ts
437import { UIUtils } from '@kit.ArkUI';
438class NonObservedClass {
439  name: string = 'Tom';
440}
441
442@Entry
443@ComponentV2
444struct Index {
445  observedClass: NonObservedClass = UIUtils.makeObserved(new NonObservedClass());
446  nonObservedClass: NonObservedClass = new NonObservedClass();
447  build() {
448    Column() {
449      Text(`observedClass: ${this.observedClass.name}`)
450        .onClick(() => {
451          this.observedClass.name = 'Jane'; // This will trigger a UI update.
452        })
453      Text(`observedClass: ${this.nonObservedClass.name}`)
454        .onClick(() => {
455          this.nonObservedClass.name = 'Jane'; // This will not trigger a UI update.
456        })
457    }
458  }
459}
460```
461